Allocators and thread safety (and not only)

malloc(3) — Linux manual page has section ‘Attributes’:

   For an explanation of the terms used in this section, see
   attributes(7).
   ┌──────────────────────────────────────┬───────────────┬─────────┐
   │ Interface                            │ Attribute     │ Value   │
   ├──────────────────────────────────────┼───────────────┼─────────┤
   │ malloc(), free(), calloc(),          │ Thread safety │ MT-Safe │
   │ realloc()                            │               │         │
   └──────────────────────────────────────┴───────────────┴─────────┘

Two other ‘attributes’ of malloc are implicit:

  • used heap memory persists for the duration of the application’s runtime

  • free - releases memory to heap for further reuse

    In the same manner we can say that Zig replacement for malloc should also to have these attributes:

  • mt-safe
  • application runtime duration
  • reusing

We can add bool property to Allocator:

const Allocator = @This();
........................................
ptr: *anyopaque,
vtable: *const VTable,
mallocReplacement: bool = false, 

DebugAllocator has all these attributes, it may be used as malloc replacement.


pub fn DebugAllocator(comptime config: Config) type {
    return struct {
    .......................................
    .......................................

        pub fn allocator(self: *Self) Allocator {
            return .{
                .ptr = self,
                .mallocReplacement = true,
                .vtable = &.{
                    .alloc = alloc,
                    .resize = resize,
                    .remap = remap,
                    .free = free,
                },
            };
        }


Minimal changes