My program crashes when I try to assign a string value to a member of a structure. My suspicion is that the member (of type string) within the structure was never properly alloc
The way you are allocating node
is incorrect: if you want to dynamically allocate non-POD types in C++, you need to use new
, since it will call the required constructors (followed by a call to delete
when appropriate).
But it might be simpler to allocate an automatic instance:
DataRow node;
If you do need a pointer, make sure to have a look at smart pointers, particularly std::unique_ptr and std::shared_ptr. See also boost::scoped_ptr.
You have to create a new struct and not use malloc at all.
So use:
DataRow* node = new DataRow;
you should also take care of cleaning it up like so:
delete node;
and in case you don't want to allocate it from the heap you can do this as well:
DataRow node;
In C++ use 'new' instead of 'malloc'. Using malloc does not run the constructor of your class, so the string is not initialized.
malloc
doesn't ensure any constructors of the members of your struct
are called. In C++ struct
is basically the same as class
, the only difference is that members are public
by default rather than private
. So you should new
the object/struct, and delete
it when done.
So before I get to answering your question I just wanted to say that you should not use Malloc in c++ unless you are forced to. This answer explains why fairly well.
In what cases do I use malloc vs new?
With that said changing this line
DataRow* node = (DataRow*)malloc(sizeof(DataRow));
To this
DataRow* node = new DataRow;
Will fix your problem