On Fri, Jun 27, 2025 at 06:17:14PM +0200, Florian Weimer wrote:
> * Alejandro Colomar:
> 
> > I think everybody agrees that glibc's calloc(3) is conforming to C11,
> > and it behaves like my proposal suggests.
> >
> >     alx@debian:~/tmp$ cat c.c 
> >     #include <stdio.h>
> >     #include <stdlib.h>
> >
> >     int
> >     main(void)
> >     {
> >             printf("%p\n", calloc(0, 42));
> >             perror("calloc(0, 42)");
> >
> >             printf("%p\n", calloc(42, 0));
> >             perror("calloc(42, 0)");
> >
> >             printf("%p\n", calloc(0, 0));
> >             perror("calloc(0, 0)");
> >     }
> >     alx@debian:~/tmp$ gcc c.c 
> >     alx@debian:~/tmp$ ./a.out 
> >     0x564b188332a0
> >     calloc(0, 42): Success
> >     0x564b188338d0
> >     calloc(42, 0): Success
> >     0x564b18833d00
> >     calloc(0, 0): Success
> >
> > In any case, I've improved the wording to be more explicit about it.
> > See alx-0029r6.
> 
> I think the wording still allows calloc (42, 0) to fail with EINVAL (or
> some other error code) because 0 is not a valid object size.

Since this is also a matter of confusion, I'd like to see it improved.
In addition to zero being unclear to some readers, it's not clear to
some users (and even implementors) that it must fail if the
multiplication overflows. This is only implied by the impossibility of
meeting the requirements for the success condition if the
multiplication would overflow.

The simple unambiguous way to define calloc would be as-if it performs
malloc followed by memset of size*nmemb bytes, with a requirement to
fail if the mathematical value of size*nmemb is not representable in
type size_t (and would thereby be subject to modular reduction).

A non-normative note should say that the intent is that it can be used
to allocate an array of nmemb objects each of size size, but that
calloc(size,nmemb) and calloc(nmemb,size) are equivalent and to not
imply any obligation to access the object as such an array or that
either value be nonzero.

Rich

Reply via email to