Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory twice

Tags:

In C and C++, Freeing a NULL pointer will result in nothing done.

Still, I see people saying that memory corruption can occur if you "free memory twice".

Is this true? What is going on under the hood when you free memory twice?

like image 245
Vijay Avatar asked Mar 18 '10 10:03

Vijay


People also ask

What happens when you free memory twice?

Calling free() twice on the same value can lead to memory leak. When a program calls free() twice with the same argument, the program's memory management data structures become corrupted and could allow a malicious user to write values in arbitrary memory spaces.

What happens if you free already freed memory?

Depending on which system you run it on, nothing will happen, the program will crash, memory will be corrupted, or any other number of interesting effects.

What happens if you free a pointer twice in C?

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.

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

int *p = malloc(sizeof(int)); //value of p is now lets say 0x12345678  *p = 2; free(p); //memory pointer is freed, but still value of p is 0x12345678          //now, if you free again, you get a crash or undefined behavior. 

So, after free ing the first time, you should do p = NULL , so if (by any chance), free(p) is called again, nothing will happen.

Here is why freeing memory twice is undefined: Why free crashes when called twice

like image 62
N 1.1 Avatar answered Sep 29 '22 13:09

N 1.1