# Double free

As explained [here](https://www.ctfrecipes.com/general-knowledge/operation-of-the-heap/chunk#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 !
