# Double free

As explained [here](/pwn/general-knowledge/operation-of-the-heap/chunk.md#free-chunk), free chunk contain the location of the next free chunk, the **forward pointer**. This mean that if chunk `a` points to chunk `b`, once chunk `a`is allocated, the next chunk of this size to be allocated will be the chunk `b`.

A **double free attack** attempt to **control** the **forward pointer.**

By **overwriting** the forward pointer **with an arbitrary memory address**, the next `malloc()` **will allocate this arbitrary location.**

{% hint style="danger" %}
The address must point to a ***valid*** chunk structure.

It must have a size attribute equal to the size of the bin used.
{% endhint %}

## How it works ?

When a chunk is freed, it's pushed onto the bin

There is what happen when the same chunk was freed twice.

```c
char *a = malloc(0x20);
free(a);
free(a);
```

{% @mermaid/diagram content="graph LR
subgraph original\_state
HEAD1(HEAD)
end
subgraph state\_1
HEAD2(HEAD) --> a1(a)
end
subgraph state\_2
HEAD3(HEAD) --> a2(a)
a2 --> a3(a)
end
original\_state -- "free(a)" --> state\_1
state\_1 -- "free(a)" --> state\_2" %}

{% hint style="info" %}
In fact now there is a security that prevent double free as see here.

```bash
$ ./test
free(): double free detected in tcache 2
Aborted
```

{% endhint %}

What happens if a `malloc()` with the same size is called again ?

The chunk `a` is **now both allocated and free at the same time.**

It's mean that user data written into the chunk will be placed at the same place that the `forward` and `backward` pointers

A user can so write an arbitrary address that will be used as `forward pointer` and then the next malloc will allocate an arbitray chunk position and so give an arbitrary write !


---

# 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/double-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.
