Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie Question: New and Delete

Status
Not open for further replies.

Weber1

Programmer
Sep 9, 2000
20
US
Ok, this is a pretty lame question, but I can't find a good answer in my reference book and program is not working in the way I think it should:

What, exactly do the "new" and "delete" functions do? I know I can allocate memory with the "new" function (similar to malloc?), but how does the "delete" function free (similar to "free" function?) up memory?

My question is in regard to a string class I have created. If I say, in the constructor:

char* stringdata = new char[length];

and in the destructor:

delete stringdata;

what exactly is the program doing with the delete function? Is it smart enough to free all of the memory allocated by the call to "new" or is it just freeing up the byte that stringdata is pointing to? Any tip would be greatly appreciated.

 
Delete will call the destructor of your class, and it will free the memory of the pointer.

But your destructor does not appear to clean up all the memory. When you delete an array, you should use:

delete [] stringdata;

Your constructor looks right to me as long as length is an integer.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top