logoalt Hacker News

Arena Allocators in C

41 points • by dimonomid • last Sunday at 6:07 PM • 12 comments • view on HN

Comments

teo_zero • last Monday at 6:06 PM

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.

bobbyraduloff • today at 9:42 AM

Using the structs for return values with `[[nodiscard]]` looks so clean.

sweetjuly • today at 7:12 AM

> 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.

➕ show 1 reply
unwind • today at 7:50 AM

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.

➕ show 1 reply
mrlonglong • last Monday at 9:18 PM

Why redefine the stdints?

➕ show 4 replies