Delete VS Null VS Free in C++

delete vs NULL vs free in c++

Your question suggests that you come from a language that has garbage collection. C++ does not have garbage collection.

If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an "orphaned" block of memory that remains allocated but is now unreachable -- a leak. Leaks only cause a program to crash if they build up to a point where no memory is left to allocate.

There's also the converse situation, where you delete a block of memory using a pointer, and later try to access that memory as though it was still allocated. This is possible because calling delete on a pointer does not set the pointer to NULL -- it still points to the address of memory that previously was allocated. A pointer to memory that is no longer allocated is called a dangling pointer and accessing it will usually cause strange program behaviour and crashes, since its contents are probably not what you expect -- that piece of memory may have since been reallocated for some other purpose.

[EDIT] As stinky472 mentions, another difference between delete and free() is that only the former calls the object's destructor. (Remember that you must call delete on an object allocated with new, and free() for memory allocated with malloc() -- they can't be mixed.) In C++, it's always best to use static allocation if possible, but if not, then prefer new to malloc().

What's the difference between delete-ing a pointer and setting it to nullptr?

It is not the same, because while you may be setting the pointer to null, the contents that the pointer pointed to would still be taking up space.

Doing

delete pointer;
pointer = NULL;

Is fine, but

pointer = NULL;
delete pointer;

Is not, since you already set the pointer to NULL, the delete command will have nothing to delete (or so it thinks). You now have a memory leak because whatever the pointer pointed to beforehand (let's say a linked list) is now floating somewhere in your memory and is untrackable by the program.

Why does the C function free() not delete values?

Think of malloc and free as signing a contract.

malloc is the promise that the chunk of memory belongs to you and won't be given to someone else. It does not guarantee anything but the size about the memory or initialize it in any way. It doesn't even prevent some other function or process from accessing that memory by address, although such access is bad behavior indeed.

free is you signing the memory back over to the allocator and nothing else. The memory is usually not "deleted" since that is a waste of cycles: the next owner will be responsible for putting in meaningful values regardless. Accessing that memory is the same sort of bad behavior as someone else accessing the memory given to you. You don't know if or when that memory is allocated elsewhere, and it's none of your business once you decide to call free.

Difference between setting a node equal to NULL vs. deleting a Node

No, it is not the same. delete X; statement actually calls a destructor of the object pointed by X and releases/frees the memory previously allocated for that object by operator new.

The X = NULL; statement simply assigns addres 0x0 to the pointer X and neither destroys the object pointed by X nor releases the memory as opposed to delete.

Deleting object vs setting pointer to null

To deallocate an object allocated by new, you should use delete.

To prevent a pointer from being "dangling", set the pointer to nullptr.

Class* c = new Class();
delete c; // free up the allocated memory from new
c = nullptr; // prevent dangling pointer

if c is not used anymore after destruction, assigning it to nullptr is not needed.

An example why a pointer is set to nullptr after delete is because of null guards like:

if (c != nullptr) {
delete c;
c = nullptr;
}

This is redundant since delete already checks if the pointer is still pointing to a valid memory location.

If it is already nullptr, then it does nothing.

From expr.delete#7.3:

Otherwise, the delete-expression will not call a deallocation
function.

[ Note: The deallocation function is called regardless of
whether the destructor for the object or some element of the array
throws an exception. — end note ] If the value of the operand of the
delete-expression is a null pointer value, it is unspecified whether a
deallocation function will be called as described above.

What is the difference between delete a pointer and set the pointer as NULL?

delete myPointer de-allocates memory, but leaves value of myPointer variable, that it is pointing to some garbage address.

myPointer = NULL only sets value of myPointer to null-pointer, possibly leaking memory, if you don't delete other pointer, which points to same address as myPointer

In ideal world you should use both those strings, like this:

delete myPointer; // free memory
myPointer = nullptr; // setting value to zero, signalizing, that this is empty pointer

But overall, use std::unique_ptr, which is modern approach to memory management.

Does free(ptr) where ptr is NULL corrupt memory?

7.20.3.2 The free function

Synopsis

#include <stdlib.h> 
void free(void *ptr);

Description

The free function causes the space pointed to by ptr to be deallocated, that is, made
available for further allocation. If ptr is a null pointer, no action occurs.

See ISO-IEC 9899.

That being said, when looking at different codebases in the wild, you'll notice people sometimes do:

if (ptr)
free(ptr);

This is because some C runtimes (I for sure remember it was the case on PalmOS) would crash when freeing a NULL pointer.

But nowadays, I believe it's safe to assume free(NULL) is a nop as per instructed by the standard.

Setting variable to NULL after free

Setting unused pointers to NULL is a defensive style, protecting against dangling pointer bugs. If a dangling pointer is accessed after it is freed, you may read or overwrite random memory. If a null pointer is accessed, you get an immediate crash on most systems, telling you right away what the error is.

For local variables, it may be a little bit pointless if it is "obvious" that the pointer isn't accessed anymore after being freed, so this style is more appropriate for member data and global variables. Even for local variables, it may be a good approach if the function continues after the memory is released.

To complete the style, you should also initialize pointers to NULL before they get assigned a true pointer value.

Is there any reason to check for a NULL pointer before deleting?

It's perfectly "safe" to delete a null pointer; it effectively amounts to a no-op.

The reason you might want to check for null before you delete is that trying to delete a null pointer could indicate a bug in your program.

Edit

NOTE: if you overload the delete operator, it may no longer be "safe" to delete NULL



Related Topics



Leave a reply



Submit