logoalt Hacker News

Some bits on malloc(0) in C being allowed to return NULL

47 pointsby ingvelast Wednesday at 6:15 AM56 commentsview on HN

Comments

bobmcnamarayesterday at 5:01 PM

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

show 3 replies
tptacekyesterday at 6:51 PM

I get the complexity of the standards issue here, but if you cared about this, wouldn't you just wrap malloc with something trivial that provided the semantic you wanted to depend on (NULL or some sentinel pointer).

Lvl999Noobyesterday at 6:50 PM

Can someone tell me a usecase where you want multiple allocations of size 0, each one with a unique address, and each one unique from any other allocation (hence necessarily removing that pointer from being allocated to anything else) but can't use malloc(1) instead?

I think it would be much better if malloc(0) just returned 1 or -1 or something constant. If the programmer needs the allocation to have a unique address, they can call malloc(1) instead.

show 2 replies
carrayesterday at 5:24 PM

Not the best choice to begin the title with "some bits" in this context. My mind was trying to understand this sentence in a completely different way...

randomNumber7yesterday at 6:44 PM

I never had the use case to allocate 0 bytes of memory.

If I would allocate 0 bytes of memory and get a pointer to it, I wouldn't care what the value of the pointer is since I am not allowed to dereference it anyways.

But then again, why would I allocate 0 bytes of memory?

show 1 reply
AaronDineshyesterday at 5:21 PM

Why should it be allowed to return a valid pointers anyways? Surely it should always return NULL?

show 5 replies
a-dubyesterday at 7:04 PM

would be interesting to see if there's a difference in how the 0-page is handled in systems under this condition...

eesmithyesterday at 6:10 PM

I maintained a program which failed on, as I recall, AIX (mentioned in the essay) because malloc(0) returned NULL.

It's been 30 years so I've forgotten the details. My solution was to always allocate size+1 since memory use was far from critical.