Visual overview of a custom malloc() implementation
silent-tower.net
silent-tower.net
I was really happy when the first code on the page, for once, did not look like it was written by someone writing C when they would much rather write something else.
This line:
struct article *my_article = malloc(sizeof *my_article);
Is almost exactly how I would have written it, and (to me) does three things very right:- Does not use a pointless, wordy, bloated cast to somehow "convert" the pointer to the proper type. The point of malloc() returning a void pointer is that no such cast is needed.
- Does not hardcode a size, but uses the sizeof operator to let the compiler compute it.
- Does not repeat the type name, which is brittle and wordy, but instead (again) lets the compiler compute it from the target pointer.
I was a bit more hesitant about this line, later in the article:
return (void *)b + sizeof(block_t) + b->size;
Not sure what language standard is targeted by the code in the article, but being able to do pointer arithmetic with void pointers is a GCC extension which at least should be mentioned.(For better or for worse, people often compile C-style code with a C++ compiler)
It's not "few" though, it's "quite a lot". C and C++ semantics are so different that you'll have to write in a specific "common C/C++ subset" for code that should compile both in C and C++ mode.
For all the flak that Objective-C usually gets by both C and C++ people it did one thing right: it respects C as a proper subset instead of creating its own bastard-fork like C++ did and then freezing it in the mid-90s.
This results in a split between "near pointers" and "far pointers". "Near pointers" are pointers which are 16 bit and assumed to be relative to the "current segment", and can thus be dereferenced directly with any memory load instruction. "Far pointers" are 32 bit and carry a segment part and a relative part, and to dereference it, you must first write the segment part to the segment register, then do the memory load instruction with the relative part, and then you probably wanna clean up after yourself by restoring the segment register to its old state.
There were multiple segment registers too, one used for data ("heap") memory operations, one for stack memory operations, one for reading machine code, and some extra segments for convenience. You had to remember which of the segment registers your near pointer was supposed to be relative to.
If this all sounds very tedious... well, it was, and that's why, yes, segmentation is still viewed as terrible :)
(I wasn't around back when this was common, but I did write some 16-bit real mode code for a bootloader for an OS course once, and I have designed and implemented some toy 8 bit CPUs which used segmentation to have more than 256 bytes of RAM, so I do have some experience with it)
IMHO a more flexible segmentation system (exposed as base-pointer plus offset) wouldn't actually be bad if properly supported by high level languages. You could treat the base pointer as 'private knowledge' inside a system and only hand out the offset as a 'public handle'. To access a specific address you need both the private base pointer and public offset handle, and the base pointer could also move around without invalidating the offset handles in the wild.
Of course all this can be done purely in software too already.
Partitioning the address space into regions with more fine-grained permission controls than what traditional MMUs do is fine and all, but it's orthogonal to segmented memory. Having large enough machine words to not have to think about near pointers and far pointers is great.
I *would* have used a prefix for namespacing though, e.g. not `block_t` but `prefix_block_t`.
Ask long as your prefix your types it's unlikely to be a problem
The C standard has many more such adhoc reserved identifiers, for instance anything starting with `is`, `str` or `wcs` followed by a lowercase letter is technically a reserved identifier, hell, even any preprocessor macro starting with an `E` followed by a digit or uppercase letter is reserved.
Theoretically those reserved identifiers in the C standard matter more than _t because they affect all C code, not just C code targeting POSIX, yet nobody ever brings those up (because these are really only theoretical problems, and should they turn into actual problems one day they are trivial to fix).
It's important to differentiate between the C standard (e.g. what C compilers care about) and the POSIX standard (which C compilers do not care about), since not all C code runs on POSIX systems. It's only on some UNIXes where those two worlds overlap.
In the real-world, using _t typenames really is a complete non-issue.
Usually alignment is a bit larger, to accommodate SSE etc. which requires larger alignment.
The algorithm I implemented is very similar to the one implemented in this article: start with a huge block of free memory; split it into multiple blocks on allocation; merge with free neighbors on deallocation. Merging blocks is the reason why doubly linked lists are needed. It worked well enough so I didn't make it a priority to organize the free lists by size. I really should implement that already but there are so many other things to do...
It's also important to discuss the fact that implementing a memory allocator in C essentially requires undefined behavior. Arithmetic will be done with arbitrary pointers and the result will be cast to structures. Compiling with strict aliasing turned off is essentially a must. Others have described to me "pointer laundering" techniques where they pass the pointer through some inline assembly just to prevent the optimizer from making incorrect assumptions. Just turning off strict aliasing seems like a better idea. It's a stupid feature anyway. If you're writing C, you're probably aliasing pointers and reinterpreting memory and the last thing you need is the compiler getting clever about it.
Alignment was pretty difficult to wrap my head around at first, especially the universal alignment concept. It also illustrates one of the limitations of C's malloc interface:
> malloc() can simply return maximally-aligned pointers in order to accommodate any data type
This wastes quite a lot of memory when the maximum alignment is not necessary... It should also be possible to segregate free lists by alignment, right? Seems like alignment should be a parameter of the memory allocation function.
This article is also really great:
https://nullprogram.com/blog/2023/12/17/
https://news.ycombinator.com/item?id=38675379
Explores the idea of breaking away from C's legacy memory allocation interfaces. If you're like me and enjoy the idea of reinventing things from scratch, it's a great read.
Also linked from its HN discussion:
https://gist.github.com/o11c/6b08643335388bbab0228db763f9921...
No issue on Firefox/Linux.
Looks like a platform-specific font rendering issue?
And here I thought the author was making a fragmentation joke.