Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any harm in calling 'free' for the same pointer twice in a C program?

If I have a c program, like:

SomeTypePtr my_type;
my_type = malloc(sizeof(someType));

/* do stuff */

free(my_type);

/* do a bunch of more stuff */

free(my_type);

Does the calling of 'free' for my_type do any harm? After I call free(my_type), does the pointer become a null pointer once again?

like image 450
Ash Avatar asked May 18 '11 03:05

Ash


People also ask

What happens if we free a pointer twice?

That means it directly access the hidden parts of the memory block and assumes that the linked list pointers there are valid. If you free a block twice then you might have the problem that someone did a new malloc , got the memory you just freed, overwrites it and the second free reads invalid pointers from it.

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.

What happens if you malloc a pointer twice?

It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr , which erases the old value that was in newPtr .

What is a double free error?

The error of double free or corruption in C++ means that our program somehow invokes the free() C++ object with an illegal pointer variable. When we use smart pointers such as shared_ptr, we must check because if we call the function get(), we are directly using the raw pointer.


2 Answers

Deallocating a memory area with free does not make the contents of the pointer NULL. Suppose that you have int *a = malloc (sizeof (int)) and a has 0xdeadbeef and you execute free (a) then after execution a still contains 0xdeadbeef but after the free call this memory address is no more reserved for you. Something like you have rented a flat with malloc used for some time, returned the flat by free then you might have a duplicate key for the flat, but it is not reserved for you.

Doing a free on an already freed memory will result in double free memory corruption.

like image 136
phoxis Avatar answered Sep 21 '22 06:09

phoxis


  1. It will not make your pointer NULL.
  2. It will free the memory pointed by the pointer, leaving the pointer set to an unallocated segment of memory.
  3. If you don't use malloc or calloc between the calls it will give you a Segmentation Fault.
  4. "Best practice is that a pointer passes out of scope immediately after being freed." means that the pointer should stay on the stack so that it should not be set NULL explicitly because it will eventually go out of scope and be freed.
like image 30
Radu Stoenescu Avatar answered Sep 20 '22 06:09

Radu Stoenescu