Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between memory leak, accessing freed memory and double free?

I'm trying to figure out what is the difference between those three kinds of problems associated with memory models.

If I want to simulate a memory leak scenario, I can create a pointer without calling corresponding delete method.

int main() {
    // OK
    int * p = new int;
    delete p; 

    // Memory leak
    int * q = new int;
    // no delete
}

If I want to simulate a double free scenario, I can free a pointer twice and this part memory will be assigned twice later.

a = malloc(10);     // 0xa04010
b = malloc(10);     // 0xa04030
c = malloc(10);     // 0xa04050

free(a);
free(b);  // To bypass "double free or corruption (fasttop)" check
free(a);  // Double Free !!

d = malloc(10);     // 0xa04010
e = malloc(10);     // 0xa04030
f = malloc(10);     // 0xa04010   - Same as 'd' !

However, I don't know what is accessing freed memory. Can anybody give me an example of accessing freed memory?

like image 701
Coding_Rabbit Avatar asked Feb 02 '26 03:02

Coding_Rabbit


1 Answers

  1. Memory leaks are bad.
  2. Double frees are worse.
  3. Accessing freed memory is worser.

Memory leaks

This is not an error per se. A leaking program is stil valid. It may not be a problem. But this is still bad; with time, your program will reserve memory from the host and never release it. If the host's memory is full before the program completion, you run into troubles.

Double frees

Per the standard, this is undefined behaviour. In practice, this is almost always a call to std::abort() by the C++ runtime.

Accessing freed memory

Also undefined behaviour. But in some case, nothing bad will happen. You'll test your program, put it in production. And some day, for no apparent reason, it will break. And it will break hard: randomly. The best time to rework your résumé.

And here is how to access freed memory:

// dont do this at home
int* n = new int{};
delete n;
std::cout << *n << "\n"; // UNDEFINED BEHAVIOUR. DONT.
like image 194
YSC Avatar answered Feb 03 '26 18:02

YSC