So from the explanation of malloc(0)
question. I find it counterintuitive that the notion of the zero size of the allocated memory chunk when returning a not-NULL value. (concluded from here)
Since, two malloc addresses cannot be the same, allocation that is returned should then take up at least one byte to guarantee that return value future calls to malloc
does not collide with any malloc(0)
in the current processs' lifetime.
Alternatively, it would imply that two mallocs—one with 0 and the other without—would in this instance return the same base address, which is conflicting as two memory locations with different size is not possible.
Could allocation size of zero in malloc result in conflicting memory locations?
No.
Consider non-zero size calls.
2 successful calls malloc(some_non-zero_value)
*1 return different pointers.
Now look as size zero. Allocating size zero is special and deserves careful digesting of the C spec.
With an allocation of size zero, 1 of 2 things happen:
So if code does not receive a null pointer when allocating size zero, the pointer is as if it was malloc(some_non-zero_value)
. Multiple successful malloc(some_non-zero_value)
are unique.
Since your code may tolerate a null pointer from malloc(0)
, and multiple calls then may both return a null pointer and so lose the uniqueness attribute of different calls returning different pointers, always use a non-zero size to maintain uniqueness.
Deeper
"... allocation that is returned should then take up at least one byte to guarantee that return value future calls to malloc does not collide with any malloc(0) in the current processs' lifetime." --> "should then take up at least one byte" is not supported by the C spec.
Consider malloc()
could return a pointer that does not actually point to real physical memory until accessed. Since the caller of malloc(0)
is prohibited from de-referencing the returned pointer, no physical memory is certainly used.
See Why is malloc not "using up" the memory on my computer?
*1 Without a intervening free()
of the first.