←back to thread

48 points ingve | 1 comments | | HN request time: 0.214s | source
Show context
bobmcnamara ◴[] No.44389188[source]
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(3): >>44389317 #>>44389346 #>>44389977 #
o11c ◴[] No.44389317[source]
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 ...

replies(3): >>44389517 #>>44389553 #>>44395128 #
LPisGood ◴[] No.44389517[source]
Noncompliant, but what could this reasonably impact?
replies(2): >>44389559 #>>44389605 #
bobmcnamara ◴[] No.44389559[source]
> Noncompliant, since `malloc(0)` is specified to return a unique pointer if it's not `NULL`.

I know I've seen that somewhere, but may I ask what standard you're referring to?

replies(1): >>44389694 #
masfuerte ◴[] No.44389694[source]
It's POSIX.

> Each [...] allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer shall be returned. If the size of the space requested is 0, the behavior is implementation-defined: either a null pointer shall be returned, or the behavior shall be as if the size were some non-zero value, except that the behavior is undefined if the returned pointer is used to access an object.

https://pubs.opengroup.org/onlinepubs/9799919799/functions/m...

replies(1): >>44390087 #
MaxBarraclough ◴[] No.44390087[source]
Not just POSIX, also the ISO C standard itself. https://en.cppreference.com/w/c/memory/malloc
replies(2): >>44390145 #>>44390234 #
masfuerte ◴[] No.44390145[source]
That doesn't say the pointer has to be unique.
replies(2): >>44390258 #>>44390287 #
1. bobmcnamara ◴[] No.44390287[source]
It is in ANSI 89, under memory management functions.