# std.heap: rework \`c_allocator\` · gitcafe/zig

[View on GitCafe](https://git.cafe/gitcafe/zig/commit/4ce7b57e86ca1d5e71100c6cab5c75aad929a430)

Repository: [gitcafe/zig](https://git.cafe/gitcafe/zig)

Visibility: public

Requested revision: 4ce7b57e86ca1d5e71100c6cab5c75aad929a430

Requested commit: 4ce7b57e86ca1d5e71100c6cab5c75aad929a430

Commit: 4ce7b57e86ca1d5e71100c6cab5c75aad929a430

Tree: 0c60b0db7bb89b8e5d0e7c6dae038adb001f0be2

Author: Matthew Lugg

Committer: mlugg

## Message

```
std.heap: rework `c_allocator`

The main goal here was to avoid allocating padding and header space if
`malloc` already guarantees the alignment we need via `max_align_t`.
Previously, the compiler was using `std.heap.raw_c_allocator` as its GPA
in some cases depending on `std.c.max_align_t`, but that's pretty
fragile (it meant we had to encode our alignment requirements into
`src/main.zig`!). Perhaps more importantly, that solution is
unnecessarily restrictive: since Zig's `Allocator` API passes the
`Alignment` not only to `alloc`, but also to `free` etc, we are able to
use a different strategy depending on its value. So `c_allocator` can
simply compare the requested align to `Alignment.of(std.c.max_align_t)`,
and use a raw `malloc` call (no header needed!) if it will guarantee a
suitable alignment (which, in practice, will be true the vast majority
of the time).

So in short, this makes `std.heap.c_allocator` more memory efficient,
and probably removes any incentive to use `std.heap.raw_c_allocator`.

I also refactored the `c_allocator` implementation while doing this,
just to neaten things up a little.

```

## Parents

- [ea94ac52c531dd7e2ac2128f097fa036f5075403](https://git.cafe/gitcafe/zig/commit/ea94ac52c531dd7e2ac2128f097fa036f5075403?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zig/tree/4ce7b57e86ca1d5e71100c6cab5c75aad929a430?format=markdown)
