I need to have a dynamic array of strings, so that I can expand it at any time. So I wanted to do it with malloc/realloc. But every time I try to run it I get segmentation fault with following errors from valgrind:
==13709== Use of uninitialised value of size 8
==13709== at 0x4EEED9B: std::string::assign(char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==13709== by 0x400953: main (test.cpp:12)
==13709==
==13709== Invalid read of size 8
==13709== at 0x4EEED9B: std::string::assign(char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==13709== by 0x400953: main (test.cpp:12)
My code looks like that:
int main()
{
string* arr;
arr=(string*) malloc(5*sizeof(string));
arr[0]="test1";
arr[1]="test2";
cout << arr[0] << arr[1] << endl;
}
I know about char**, but it is kind of a pain to use, so I wanted to use strings. Any hint on how to make it work?
std::vector< std::string >?vector<string>and save yourself a whole lot of grief.mallocis almost never used in C++, this reason being one of them. As a direct replacement,newworks with non-POD types (likestd::string) and a vector works even better. I'm not sure what kind of memory you're saving by not using a vector.vectorcosts you roughly the space needed for three pointers; which is pretty much the minimum you need for a performant dynamic array. You're not paying for anything you're not using.std::vector).