tech-userlevel archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: unhide reallocarray
Date: Wed, 31 Aug 2022 14:35:15 +0200
From: Joerg Sonnenberger <joerg%bec.de@localhost>
Message-ID: <Yw9Vgw9ljtt1Q9fg%bec.de@localhost>
| So what did they specify for reallocarray in POSIX now?
The basic specification is simple:
The reallocarray( ) function shall be equivalent to the call
realloc(ptr, nelem * elsize) except that overflow in the
multiplication shall be an error.
It later specifies ENOMEM for the error in that case.
| What does it return if either element size or number of elements is 0?
RETURN VALUE
Upon successful completion, realloc( ) and reallocarray( )
shall return a pointer to the (possibly moved) allocated space.
If size is 0, or either nelem or elsize is 0, then either:
[size is the param to realloc() and nelem and elsize to reallocarray]
� A null pointer shall be returned and, if ptr is not a null pointer,
errno shall be set to an implementation-defined value.
� A pointer to the allocated space shall be returned, and the
memory object pointed to by ptr shall be freed. The application
shall ensure that the pointer is not used to access an object.
| Being able to return NULL in that case is quite desirable
so you can do that, but if you do, you're not permitted to free any
memory that was allocated earlier (ie: the only time this is not an
error is when the ptr arg was NULL).
Or you can free the memory, but return a pointer to the memory just
freed (the assumption is that since the size is 0, the application knows
there is no memory at *ptr after the realloc*() has succeeded, so will
not attempt to deref the pointer.
This is all, according to the application usage section, because of what
the C standard is planning to do:
The description of realloc( ) has been modified from previous versions
of this standard to align with the ISO/IEC 9899:1999 standard. Previous
versions explicitly permitted a call to realloc(p, 0) to free the space
pointed to by p and return a null pointer. While this behavior could be
interpreted as permitted by this version of the standard, the C language
committee has indicated that this interpretation is incorrect. Applications
should assume that if realloc( ) returns a null pointer, the space pointed
to by p has not been freed. Since this could lead to double-frees,
implementations should also set errno if a null pointer actually indicates
a failure, and applications should only free the space if errno was changed.
and in Future Directions:
This standard defers to the ISO C standard. While that standard currently
has language that might permit realloc(p, 0), where p is not a null
pointer, to free p while still returning a null pointer, the committee
responsible for that standard is considering clarifying the language to
explicitly prohibit that alternative.
kre
Home |
Main Index |
Thread Index |
Old Index