简体   繁体   中英

C++ error to set string in struct by pointer

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.

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM