Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling free on a pointer twice

Tags:

I have been taught in lectures, that calling free() on a pointer twice is really, really bad. I know that it is good practice, to set a pointer to NULL, right after having freed it.

However, I still have never heard any explanation as to why that is. From what I understand, the way malloc() works, it should technically keep track of the pointers it has allocated and given you to use. So why does it not know, whether a pointer it receives through free() has been freed yet or not?

I would love to understand, what happens internally, when you call free() on a location that has previously already been freed.

like image 227
Joe Avatar asked Dec 15 '15 09:12

Joe


People also ask

What happens if you free a pointer twice?

Double free is undefined If we free the same pointer two or more time, then the behavior is undefined. So, if we free the same pointer which is freed already, the program will stop its execution.

What happens if I free a pointer?

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. which means that a later call to malloc (or something else) might re-use the same memory space. As soon as a pointer is passed to free() , the object it pointed to reaches the end of its lifetime.

Can a pointer be used after free?

UAFs and Dangling PointersUse-after-free is the result of dereferencing a pointer that points to an object that had already been freed (also called a dangling pointer): Two common reasons that lead to dangling pointers are: Not updating the reference count of a currently in-use object.

How can double free be avoided?

Double Free A simple technique to avoid this type of vulnerability is to always assign NULL to a pointer after it has been freed. Subsequent attempts to free a null pointer will be ignored by most heap managers.


1 Answers

When you use malloc you are telling the PC that you want to reserve some memory location on the heap just for you. The computer gives back a pointer to the first byte of the addressed space.

When you use free you are actually telling the computer that you don't need that space anymore, so it marks that space as available for other data.

The pointer still points to that memory address. At this point that same space in the heap can be returned by another malloc call. When you invoke free a second time, you are not freeing the previous data, but the new data, and this may not be good for your program ;)

like image 170
enrico.bacis Avatar answered Sep 19 '22 23:09

enrico.bacis