1

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.

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.