←back to thread

48 points ingve | 1 comments | | HN request time: 0.377s | 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 #
sgerenser ◴[] No.44389346[source]
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?
replies(2): >>44389482 #>>44389702 #
bobmcnamara ◴[] No.44389482[source]
At the end of main, if the count wasn't balanced, then you knew you had a mismatch between malloc()/free().

If malloc() had returned a real pointer, you'd have to free that too.

> wouldn’t it be better just to return NULL and guarantee that 0-sized allocations never use any memory at all?

Better: takes less memory Worse: blinds you to this portability issue.

replies(1): >>44389856 #
Someone ◴[] No.44389856[source]
> At the end of main, if the count wasn't balanced, then you knew you had a mismatch between malloc()/free().

A mismatch between malloc(0) and free(-1).

You’d know nothing about calls to malloc with non-zero sizes.

replies(2): >>44390689 #>>44392512 #
1. bobmcnamara ◴[] No.44392512[source]
Those are identifiable by the end state of the heap not being empty.