问题
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?
回答1:
Works for me.
But I have never done this:
istringstream input(s, istringstream::in);
Try
istringstream input(s);
回答2:
So the answer turned out to be a bug in Xcode. Here's a similar problem and its solution.
来源:https://stackoverflow.com/questions/2633092/istringstream-in-c