Remix.run Logo
irenaeus 3 days ago

I've read some allocator walkthroughs before but I thought that this line stood out:

"to get individual free() working, the allocator needs to remember something about every allocation it handed out. and that’s the moment metadata stops being optional."

That's just a very nice distillation of an important concept.

HexDecOctBin 4 hours ago | parent | next [-]

This becomes particularly important when the allocation and metadata cannot (or should not) be stored in the same address space. An example of this is allocating memory on GPUs.

The conventional approach for allocating memory on GPUs for games and other applications is to use a real-time allocator such as TLSF. However, it is not usually discussed that TLSF is real-time because it stores metadata in-band. It is possible to create a variant of TLSF that preserves its real-time properties while storing metadata out-of-band, but this requires careful consideration.

geocar 4 hours ago | parent | prev | next [-]

Oh? How do you think munmap does it?

If you can convince the caller to keep track of that metadata themselves you obviously don’t need to. That can be important.

Something I noticed is that _very often_ the code that is calling malloc(n) is keeping track of n somehow for its own reasons (bounds checking, grow/gap pointers, etc) so merging the value halves stack churn and it’s an easy win.

simiones an hour ago | parent | next [-]

Well, even that doesn't really work, because optimized allocators typicallly don't allocate exactly the amount that you ask for, they allocate some larger chunk to help with both alignment and fragmentation.

So, most likely, there are two sizes in reality: the size of your user data that you care about; and the size of the memory chunk in which your user data resides, that free() cares about. So, unless you're willing to go for an API like this, you can't rely on the consumer:

  int* ptr_to_dest = NULL;
  size_t size = 10 * sizeof(int);
  size_t allocated = malloc(&ptr_to_dest, size);
  if (allocated <= 0 || !ptr_to_dest) {
    //handle allocation error
  }
  //... use ptr_to_dest, size
  free(ptr_to_dest, allocated); //careful not to pass size here!
xxs 2 hours ago | parent | prev | next [-]

> keep track of that metadata themselves you obviously don’t need to

likely it'd a be perf. hit in most cases. They'd have to copy to the tail end (likely) of the allocated area. Or the start and offset the pointer, they'd need to know the size of the metadata and account for that, including aligning it.Hence, the tail feels 'nicer'

It's possible to manually use mmap and forgo malloc entirely, rolling your own arena manager.

byroot 4 hours ago | parent | prev [-]

That's why C23 introduce free_sized [0].

[0] https://en.cppreference.com/c/memory/free_sized

Someone an hour ago | parent [-]

>> If you can convince the caller to keep track of that metadata themselves you obviously don’t need to. That can be important.

> That's why C23 introduce free_sized

Is it? C23 still has free, so there’s no guarantee callers wil use free_sized, so the allocator still has to be able to obtain a block’s size from a pointer.

Or do I overlook something?

lifthrasiir 4 hours ago | parent | prev | next [-]

In the other words, free() is a flawed API. :-)

adrian_b an hour ago | parent [-]

Actually yes, the malloc/free API (inherited from the ALLOCATE and FREE statements of PL/I) is too simple.

The metadata that malloc always attaches to the allocated memory would normally be useful for the user (i.e. having access to values like the currently allocated size and the total size of the allocation).

Very frequently, the user must duplicate inside the allocated memory the same information that already exists in the metadata, wasting memory. Also time may be wasted with requests for reallocation, instead of just adjusting the currently allocated size, when this is sufficient.

With a better API, the metadata would have been visible for the user. Being hidden from the user is not a protection in a language like C, where using pointer arithmetic can trash any memory location. Being exposed as non-mutable would have been a better protection.

Moreover, a better metadata structure for malloc should have always included a reference count, to be handled automatically by the compiler, and the malloc/free functions should have been invoked only implicitly, never explicitly.

wahern 22 minutes ago | parent [-]

To play devil's advocate, the problem with exposing more info is you limit the allocator design space.

1) If the app knew about and could use the additional underlying capacity, memory checkers wouldn't be able to find small overflows

2) Calling realloc instead of knowing existing capacity doesn't really provide better performance, at least not asymptotically.

3) If you need to know the requested allocation size, usually its for a dynamic array. Constantly requesting the size from the allocator would often have horrible performance if the size wasn't stored in adjacent metadata, but instead required a lookup operation, as is the case with hardened allocators. In practice hardened allocators probably wouldn't be a thing, or alternatively it would be idiomatic to store the size separately anyhow.

4) Reference counts would impose significant space and layout limitations despite most allocations never needing it.

There's another group who would argue the allocator should require passing the size and alignment to the free function, so allocators can be optimized better. Most of the time this is known statically. I think C2y will add APIs like this, though there's also a proposal to standardize an interface to query allocation capacity. Altogether I wouldn't be surprised if someday people appreciated the balance struck by malloc/free/realloc, especially as a minimal interface for overlaying application-specific allocators or injecting instrumentation. It has a certain elegance, in the sense of nothing left to remove.

nathaah3 3 days ago | parent | prev [-]

glad you found it useful :)