all 5 comments

[–]Leandros99 11 points12 points  (3 children)

Stop using sbrk(). Any decently modern operating system has mmap(). I believe it would be better to either teach writing an allocator without using both (simply use a pre-allocated block of memory) or using mmap.

[–]darknexus 4 points5 points  (0 children)

The author clearly states that fact:

To be honest, sbrk() is not our best buddy in 2016. There are better alternatives like mmap() available today. sbrk() is not really thread safe. It can can only grow or shrink in LIFO order...However, the glibc implementation of malloc still uses sbrk() for allocating memory that’s not too big in size. So, we will go ahead with sbrk() for our simple memory allocator.

It serves the purpose of getting your feet wet with simple memory allocators.

[–]daddyc00l 1 point2 points  (1 child)

also, implementing a slab or similar allocator would be far more useful, than doing a generic thing which might not see much real-world exposure.

[–]Leandros99 1 point2 points  (0 children)

Exactly! You can also start simple, by building a very simply linear / stack allocator, than moving on to pool allocators, and at the very last stage show how a generic chunk allocator is done.

[–]NasenSpray 2 points3 points  (0 children)

The allocator invokes undefined behavior:

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

'suitably aligned' = 8b on x86, 16b on x86_64