Hi Paul, On Fri, Jun 20, 2025 at 06:34:25PM -0700, Paul Eggert wrote: > On 2025-06-20 18:06, Alejandro Colomar wrote: > > + to both return a null pointer and set errno to ENOMEM. > > Given the proposed change, I don't see why ENOMEM must be added to the C > spec. The spec changes malloc and realloc so that returning null means > failure (i.e., out of memory) and returning non-null means success. In that > case, there seems to be no pressing need for ENOMEM in the C standard (as > opposed to POSIX). > > If ENOMEM is really needed, its presence should be justified in the > proposal.
I wrote it, although maybe it would need to be clearer? Here's the part that justifies it: Here's the code that should be written for AIX or glibc: errno = 0; new = realloc(old, size); if (new == NULL) { if (errno == ENOMEM) free(old); goto fail; } ... free(new); [...] If the realloc(3) specification was changed to require that realloc(p,0) returns non-null on success, and that realloc(p,0) only fails when out-of-memory, and to require that it sets errno to ENOMEM, then code written for AIX or glibc would continue working just fine, since the errno check would be redundant with the null check. Simply, the conditional (errno == ENOMEM) would always be true when (new == NULL). If that old code runs on a new system that doesn't set ENOMEM, it will leak 'old'. Admittedly, that code is currently only portable to POSIX systems, which already require ENOMEM, and I don't expect POSIX would lift that requirement (and would recommend not lifting it), so I expect people won't run that code in arbitrary C2y platforms. However, to fully support that code, we need to set ENOMEM. Please let me know if this sounds reasonable. > Alternatively, the proposal could be divided into two: the main > proposal is the null-if-and-only-if-failure part, and ENOMEM could be the > secondary proposal. I added the ENOMEM part because of the above, to make sure that the new realloc(3) specification is fully backwards compatible to every existing implementation, so that you can take your AIX or glibc or musl or whatever code, and say "hey, I'll run this code on any C2y-conforming platform; it should Just Work". > One other thing: Doug McIlroy's point was that realloc(p,n) should never > fail when p already addresses storage of size n or greater. Hmmm, I hadn't read it that way. > As a corollary, > realloc(p,0) should never fail when p is non-null. It might be helpful to > add this as a third proposal. A lot of apps already assume McIlroy's point, > after all. Yes, sounds like a useful guarantee. Shrinking an object shouldn't ENOMEM, as the implementation could just return the old pointer. I'll keep this for a separate paper. Cheers, Alex -- <https://www.alejandro-colomar.es/>
signature.asc
Description: PGP signature