Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

freeing a null pointer

Tags:

c

pointers

What happens inside memory if we try to free a pointer which is pointing to NULL? Is that ever valid?

Why does it not show any warning/error messages?

like image 450
Vijay Avatar asked Mar 01 '10 08:03

Vijay


People also ask

Can you free a null pointer C++?

If ptr is a null pointer, no action occurs.The standard has always required free to behave this way.

Should I set a pointer to null after freeing it?

Dangling pointers can lead to exploitable double-free and access-freed-memory vulnerabilities. A simple yet effective way to eliminate dangling pointers and avoid many memory-related vulnerabilities is to set pointers to NULL after they are freed or to set them to another valid object.

How do you free a pointer?

delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

What happens when you free a pointer in C?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.


2 Answers

From C99 section 7.20.3.2 : The free function

Synopsis

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

Description

2 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.

like image 127
Prasoon Saurav Avatar answered Sep 27 '22 21:09

Prasoon Saurav


From http://linux.die.net/man/3/malloc:

If ptr is NULL, no operation is performed.

like image 45
Martin B Avatar answered Sep 27 '22 21:09

Martin B