logoalt Hacker News

bobmcnamarayesterday at 5:01 PM3 repliesview on HN

Ages ago I worked with a system where malloc(0) incremented a counter and returned -1.

free(-1) decremented the counter.

This way you could check for leaks :p


Replies

o11cyesterday at 5:17 PM

Noncompliant, since `malloc(0)` is specified to return a unique pointer if it's not `NULL`.

On most platforms an implementation could just return adjacent addresses from the top half of the address space. On 32-bit platforms it doesn't take long to run out of such address space however, and you don't want to waste the space for a bitmap allocator. I suppose you could just use a counter for each 64K region or something, so you can reuse it if the right number of elements has been freed ...

show 3 replies
sgerenseryesterday at 5:21 PM

I might be missing something, but how does this help in checking for leaks? I mean, I guess you could use it to check for leaks specifically of 0-sized allocations, but wouldn’t it be better just to return NULL and guarantee that 0-sized allocations never use any memory at all?

show 2 replies
sweetjulyyesterday at 6:28 PM

Does this work in practice? Now you have a bunch of invalid but non-NULL pointers flying around. NULL checks which would normally prevent you from accessing invalid pointers now will pass and send you along to deref your bogus pointer.

Even hacking the compiler to treat -1 as equal to NULL as well wouldn't work since lots of software won't free NULL-like pointers.

show 1 reply