Reputation: 21
I have a problem trying to set a string inside a struct, bellow is my code:
struct movieNode
{
string name;
};
int main()
{
struct movieNode* newMovieNode = (struct movieNode*)malloc(sizeof(movieNode));
newMovieNode->name = "123";
}
When a run this, the following message appears:
"Unhandled exception at 0x5EDB11E2 (msvcr110d.dll) in Trabalho.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD."
Someone can help me fix this?
Thanks a lot.
Upvotes: 1
Views: 132
Reputation: 435
To elaborate on the above answer, malloc() simply reserves a number of bytes and returns a pointer to the first one without executing any further logic. While this is OK for dumb structures containing POD types only, more complex C++ classes rely on a constructor to initialize them to a good state when they are allocated.
The 'new' keyword allocates the memory and calls the constructor for the type being instantiated. In this case, it would invoke the default constructor generated by the compiler for the movieNode struct, which will in turn invoke the default constructors for all member variables - thus initializing 'name' to an empty string as expected.
EDIT: Along the same lines, you'll want to use 'delete' to free the memory to ensure the relevant destructors gets called.
Upvotes: 0
Reputation: 119382
You allocated memory for the movieNode
, but you didn't construct it. Use new
instead. Also, the elaborated type specifier is unnecessary in C++.
movieNode* newMovieNode = new movieNode;
Upvotes: 4