Arena Allocators in C

(eliasebner.com)

31 points | by dimonomid 2 days ago

4 comments

  • teo_zero 1 day ago
    Please be aware that pointer arithmetic is not defined on void * pointers, although many compilers allow it. You had better use char * for "data".

    Also, your code is prone to overflow when you add data, used, alignment and size.

    And finally, the realloc function could be reworked to do nothing if new_size is <= old_size.

  • sweetjuly 1 hour ago
    > This will be used to align the data. For some reason, our computers are much better at dealing with data that is aligned at 8 bytes. This means that the start of each new allocation has to be at a multiple of 8 bytes.

    Casting a pointer which is not aligned to its natural alignment has undefined behavior in C. It's not just an issue of unaligned accesses being slow; in practice, your program might also crash or access unexpected data on real platforms with real compiler implementations.

  • unwind 31 minutes ago
    More obvious problems with the code as shown:

    - The macros doing arithmetic (KiB, MIN etc) don't put their arguments in parentheses, that is very dangerous.

    - The code assumes that int and i32 are the same size.

    - Don't cast the return value of malloc(). Please Google this.

    I appreciated the use of structs by value, that's a nice design.

    I agree there's a risk of overflow in the arithmetic around sizes/alignment, but with a 64-bit `usize` that should be mostly theoretical.

    • flohofwoe 5 minutes ago
      > The code assumes that int and i32 are the same size.

      Tbf this is extreme nitpicking. It's very unlikely that the code will ever be built on a compiler where int is not 32 bits. Replacing the sizeof(int) with sizeof(i32) is better of course, and tbh it looks like an oversight, not intentional.

      > Don't cast the return value of malloc(). Please Google this.

      This is required when the code should also build in C++ mode (which some weirdos seem to prefer for "improved type safety") - in any case, the explicit cast is also entirely valid C code, so not wrong.

      > The macros doing arithmetic (KiB, MIN etc) don't put their arguments in parentheses, that is very dangerous.

      Agreed.

      I would add:

      > Don't typedef C primitive types to your own shortcuts (like int32_t => i32), at least not when those typedefs leak into the public API.

  • mrlonglong 1 day ago
    Why redefine the stdints?
    • veltas 46 minutes ago
      They wanted shorter aliases for them to make their code clearer, I suppose.