# Use after free

**Use-After-Free (UAF)** is a vulnerability related to incorrect use of dynamic memory. If after freeing a memory location, the program does not clear the pointer to that memory, an attacker can still use this pointer with possibly arbitrary values.

## How it works ?&#x20;

As explained [here](https://www.ctfrecipes.com/pwn/general-knowledge/operation-of-the-heap/chunk-allocation-and-reallocation), when a chunk is freed, it's stored into a bins ( fastbins for shorter chunks, unsorted bins for the others. ) and when the program need a new chunck, it will take if from that bins first depending on the required size.&#x20;

Then, if the size is compliant, the allocated bin is the same than the previously freed chunk.&#x20;

So, the new pointer has the exact same value as the old pointer and then, if the old pointer isn't clear, it will point with this new value.&#x20;

This behavior can easily be highlight by the followed code :&#x20;

```c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


int main(void) {
    char *pointer_1 = (char *)malloc(20);

    strcpy(pointer_1, "value 1");

    printf("pointer 1 : %p, value : %s \n", pointer_1, pointer_1);

    free(pointer_1); // Here the pointer_1 is freed but not clear. 

    char *pointer_2 = (char *)malloc(20);
    strcpy(pointer_2, "value 2");

    printf("pointer 1 : %p, value : %s \n", pointer_1, pointer_1);
    printf("pointer 2 : %p, value : %s \n", pointer_2, pointer_2);

}
```

```bash
$ ./test
pointer 1 : 0x12fe2a0, value : value 1 
pointer 1 : 0x12fe2a0, value : value 2 
pointer 2 : 0x12fe2a0, value : value 2
```

{% hint style="info" %}
Note : `pointer_2` was assigned as the same chunk as `pointer_1` because the `pointer_1` chunk was freed before the `pointer_2` chunk allocation

**Unless `pointer_1` was freed, its value still accessible but it point to the new data declared by `pointer_2`**
{% endhint %}

## Resources

{% embed url="<https://heap-exploitation.dhavalkapil.com/attacks/first_fit>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ctfrecipes.com/pwn/heap-exploitation/use-after-free.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
