Jack said:
That is one of the two defined actions that malloc() may take. The
other is to return a null pointer.
Actually, I was completely wrong, but maybe notin the way you may have had
in mind primarily.
As far as I can tell from the standard, which I have read now, every call
to malloc, regardless of the argument, may return a null pointer any time.
As far as I can see, the standard makes no guarantees that calls to malloc
"succeed". So there is no difference between malloc(0) and malloc(n). The
standard just allows explicitly that every call malloc(0) may fail,
however, I cannot see that it does not allow that for other values too. In
fact, I do not see any language in the standard that would rule out the
following most useless implementation:
void* malloc( size_t size ) {
return( NULL );
}
Besides, the OP explictly mentioned that malloc(0) did not return 0 and
asked what was going on. So, I was describing what happens for a succesful
call to malloc(0), and I was mistaken on a subtle point. I thought,
incorrectly, that malloc(0) had allocated a chunk of size 0. In particular,
I thought that subsequent calls to malloc(0) may return the same pointer.
That, however, may not be allowed:
If the size of the space requested is zero, the behavior is
implementation-defined: either a null-pointer is returned, or
the behavior is *as if the size were some nonzero value*, except
that the returned pointer shall not be used to access an object.
Thus, if malloc(0) does not return 0, it shall behave as though it was
called with a non-zero argument. I read this to imply that two successive
calls to malloc(0), neither of which returns 0, must return different
values. This is an extra requirement that would not otherwise follow from
the usual requirement that allocated blocks are to be disjoint.
What do you think that a null pointer has to do with location 0? A
null pointer does not point to location 0. It does not even have an
all-bits zero representation on all platforms.
If there is a location 0 on a platform and it is valid for a C (or
C++) object to reside there, then a pointer to such an object would be
a pointer to location 0 and it would most specifically not be a null
pointer.
You are right, I was sloppy.
Just an asside triggered by your remark: is the numerical constant 0 (say
as an int or unsigned int) required to have an all-bits zeror
epresentation?
Best
Kai-Uwe Bux