new and delete in c++

Let's say I have a pointer pntr which points to an object of type Node.
i.e. Node* pntr=new Node;

The object node consists of a an int number and char *name. If I set the number=10 and name=new char[10] and then name="Hello" for the pointer pntr, and then I write delete pntr, will all the data inside the object Node get deallocated?

My main question is that will name also get deallocated?
If you are handling that in the destructor it will, otherwise it won't
You should use std::string for this sort of things, so you don't have to care about deallocating it
When you said Node->name=new char[10]; Node->name="Hello"; you lost your pointer to the allocated space. name="Hello"; doesn't copy "Hello" into the space you allocated, it makes name point to constant bytes 'H' 'e' 'l' 'l' 'o' '\0'.
After doing this, delete[] Node->name; will crash, trying to delete a constant in unmodifiable memory.
To copy into the space pointed by a char pointer, use strncpy from string.h:
strncpy(Node->name,"Hello",10);
Last edited on
When you do 'delete pntr' it will deallocate Node object but will not deallocate the name memory. you can put the 'delete name' in Node destructor.

instead of Node->name="Hello" u can use strcpy(Node->name, "Hello").

i recommend std::string

justin
Topic archived. No new replies allowed.