Does "delete" in C++ undo the work of "new" funtion? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Does "delete" in C++ undo the work of "new" funtion?

Delete is used to release a pointer from a heap and not from stack. New creates a new memory allocation in a C++ program. eg new int; delete *prt;

5th Mar 2017, 2:17 PM
Charles Mwaniki
Charles Mwaniki - avatar
1 Answer
+ 1
Memory allocations in C++ is a beast in itself. But simply put: In terms of raw memory, new typically allocates memory using the C routine malloc which requests memory from the operating system. There's quite a few differences between operating systems as to how hardware memory is managed however at a high level you get a reserved chunk of memory the size of your data type. Delete typically calls the C routine free which returns that allocated block of memory to the operating system. In terms of malloc and free, yes delete undoes what new did. However, in C++ we have objects that have constructors and destructors and there's no guarantee that the destructor undoes all of the work that was done when the constructor was called. I guess we could say the answer is yes and no, depending on where you draw the line.
5th Mar 2017, 4:34 PM
Alexandre Sabourin
Alexandre Sabourin - avatar