size_t

Doug Gwyn gwyn at smoke.BRL.MIL
Wed Jul 12 15:16:48 AEST 1989


In article <1062 at cbnewsl.ATT.COM> dfp at cbnewsl.ATT.COM (david.f.prosser) writes:
>It is possible for calloc to allocate an object bigger than can
>be described by size_t, but it is not required to do so, ...
>In fact, a valid implementation can "choose" to
>"core dump" when the multiplication overflows in calloc!

Hey, Dave -- let's not get carried away here!

The Standard requires that it either allocate storage or, *if the space
cannot be allocated*, return a null pointer.  The meaning of "unable to
allocate space" is not specified, which leaves it up to the implementor.

There is no direct way to feed the actual (dynamically-allocated) object
pointed to by the pointer returned from one of the *alloc() routines to
the sizeof operator, so there is no operational way that the semantics
of sizeof can be "probed" by the huge object that we're presuming may be
actually allocated.  One can try to cast the pointer from void* into a
pointer to a huge array, but that permits compile-time determination
that the object size limit (e.g. representability in a size_t) is being
violated, and in any case is something that would only be done AFTER
*alloc() is called.  I see no reason to say that all these size
considerations permit the implementation of *alloc() from doing its job
properly, i.e. either correctly allocating contiguous storage or else
returning a null pointer.

>... a strictly conforming program cannot attempt to allocate an object
>bigger than size_t as in the example because the behavior of the library
>is undefined.

I don't see that at all, unless related to the 32,767 bytes mentioned in
2.2.4.1 (about which more below).  sizeof is not required to work
properly when applied to huge objects, but if a program avoids trying to
do that I don't see that it becomes non-conforming just because it
handles huge objects (that WOULD break sizeof IF fed to it, but which
they AREN'T).

>In any strictly conforming program, sizeof *must* be able to return the
>number of bytes in *any* object

... to which it is applied!  I don't see how a program could be
considered to be in violation for something that it doesn't do.

Re: 2.2.4.1:

The 32,767-byte object size can be argued to be among the "minimum
implementation limits" that a strictly conforming program shall not
exceed.  On the other hand, one can argue that *alloc() is obliged
to return a null pointer if an implementation "hard limit" really
would be exceeded by the *alloc() request.

This issue probably deserves consideration by X3J11 for a formal ruling.
I would be most upset if *alloc() gave me a non-null pointer which then
wouldn't work right.  It is simpler to let calloc() tell me when at run
time I've exceeded such a limit than to have to keep performing such
checks myself in my application code.



More information about the Comp.std.c mailing list