Philipp Klaus Krause schreef op 2025-09-01 17:19:
void *realloc(void *ptr, size-t size);
C90: "[…] If the space cannot be allocated, the object pointed to by
ptr is unchanged. If size is zero and ptr is not a null pointer, the
object it points to is freed."
C99TC2 (also C99TC3 and C11): "[…] If memory for the new object cannot
be allocated, the old object is not deallocated and its value is
unchanged."
ISO/IEC 9899:TC3:
J.3 Implementation-defined behavior
A conforming implementation is required to document its choice of
behavior in each of
the areas listed in this subclause. The following are
implementation-defined:
[...]
J3.12 Library functions
[...]
— Whether the calloc, malloc, and realloc functions return a null
pointer or a
pointer to an allocated object when the size requested is zero (7.20.3).
To me this says that as long as we document the current implementation
it is all right.
C17: "If size is zero and memory for the new object is not allocated,
it is implementation-defined whether the old object is deallocated. If
the old object is not deallocated, its value shall be unchanged."
C23 (same in current C2Y draft): "[…] if the size is zero, the
behavior is undefined. If memory for the new object is not allocated,
the old object is not deallocated and its value is unchanged."
Currently, our malloc and realloc cannot allocate an object of size
zero, they return NULL on such a request, and realloc does free. To me
that looks compliant with C90, C17 and C23, but not C99.
I would like to change that to allowing allocation of zero-sized
objects instead. Then, malloc(0) and realloc(ptr, 0) would return a
non-null pointer. This would be compliant with C99, C17 and C23, but
not C90.
IMHO the current implementation is compliant with all.
From my side, this change is not motivated by a preference for the new
semantics, but by it being the simplest to implement, thus reducing
code size for malloc and realloc a bit.
Philipp
Maarten
_______________________________________________
Sdcc-user mailing list
Sdcc-user@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sdcc-user