-1

Why does this work...

string str("special_string");
string arr[10];
arr[0] = str;

while this causes a seg-fault?

string str("special_string");
string *buf = (string*)malloc(sizeof(string) * 10);
buf[0] = str; /* or *buf = str; */

Aren't both instances a by-value copy?

c_dubs
  • 360
  • 2
  • 7
  • You shouldn't use malloc with `string`. – ashiquzzaman33 Feb 12 '16 at 20:07
  • Maybe my question didn't hint at my actual intent, which was to create a heap allocated array of strings. – c_dubs Feb 12 '16 at 20:21
  • @c_dubs Use a `std::vector` instead. – πάντα ῥεῖ Feb 12 '16 at 20:37
  • Ordinarily I would, but I'm implementing a parallel merge sort, and the overhead of accessing vector elements seems to increase running time by a factor of about two. My implementation is templated, and worked for fundamental types, but suddenly failed when I tried using it for objects. Now I know why lol. – c_dubs Feb 12 '16 at 20:47

1 Answers1

0

while this causes a seg-fault?

because you have a problem here:

string *buf = (string*)malloc(sizeof(string));

you only allocate memory but do not initialize object of type std::string properly as malloc() does not call ctor. If you use operator new instead you code would work:

string str("special_string");
string *buf = new string;
*buf = str;

and of course you should use delete instead of free() when you will need to destroy that object.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • I'm trying to create a heap allocated array of strings (I know my original question didn't really hint at this intent). – c_dubs Feb 12 '16 at 20:23
  • Okay, I get it now. It's not a by-value copy, it's invoking the copy constructor for string, causing a seg-fault when it tries to interpret the uninitialized memory as a string and access its data buffer. – c_dubs Feb 12 '16 at 20:34
  • @c_dubs no it is invoking assignment operator (which may invoke copy ctor, but most probably would not), but yes it crashes because object is uninitialized – Slava Feb 12 '16 at 21:05