views:

177

answers:

2

Hello,

I'm sure I'm just doing something stupid here, but I can't quite figure out what it is. When I try to run this code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
 string s("hello");

 istringstream input(s, istringstream::in);

 string s2;
 input >> s2;

 cout << s;
}

I get this error:

malloc: *** error for object 0x100016200: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

The only thing I can think of is that I allocated s2 on the stack, but I thought strings manage their own content on the heap. Any help here would be appreciated.

Thanks,

helixed

EDIT: Fixed the last line of main, where cout << s should have been cout << s2. It runs without error if I initialized s2 to "hi", but not otherwise. Is this just a weird gcc compilation problem?

Thanks,

helixed

+1  A: 

Works for me.

But I have never done this:

istringstream input(s, istringstream::in); 

Try

istringstream input(s); 
Martin York
`ios_base::in` is the default for the `which` argument, so it shouldn't matter
Michael Mrozek
Didn't fix the problem.
helixed
@helixed: So why did you accept this answer, if it didn't fix your problem?
jalf
My original question made the assumption that there was an error in my code, but the problem was somewhere else. So he answered my question correctly.
helixed
+2  A: 

So the answer turned out to be a bug in Xcode. Here's a similar problem and its solution.

helixed