Seeking code correctness and best practices.
I would like to re-allocate various amounts of memory (0 or more) such that on systems that may return NULL
for an allocation of 0 does not falsely imply a memory allocation error.
Given:
void *
(with a valid value or NULL already)size_t
(new desired size)
Receive:
void *
(new pointer)int
(failure status)
#include <assert.h>
#include <stdlib.h>
int ReallocAndTest(char **Buf, size_t NewSize) {
assert(Buf);
char *NewBuf = realloc(*Buf, NewSize);
if ((NewBuf == NULL) && (NewSize > 0)) {
return 1; // return failure
}
*Buf = NewBuf;
return 0;
}
I came across the below references, which imply a realloc()
return of NULL
is not always a failure. The lone special case occurs with size
is 0. The return value may or may not be NULL
.
C11dr 7.22.3.5 The realloc function 4 The
realloc
function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.C11dr §J.1 Unspecified behavior. — The amount of storage allocated by a successful call to the calloc, malloc, or realloc function when 0 bytes was requested (7.22.3).
C11dr §J.3.12 Implementation-defined behavior. 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.22.3).
Discusses how a memory allocation of 0 is useful.
Answer: when a routine has amalloc(size)
, testing forsize != 0
is not needed.
what's the point in malloc(0)?Asks if
realloc(ptr), 0)
is the same asfree(ptr)
.
Answer: Not necessarily.
What happens if I re-alloc and the new size is 0. Is this equivalent with a free?Allocation wrapper set.
Answer: Does not addressrealloc(ptr, 0)
.
Are these memory-allocation wrapper functions kosher with all C compilers?
[Answer]
Use
void*
rather thanchar *
.With a 0 size, avoid returning the implementation defined
..a)NULL
or
..b)ptr
that cannot be referenced.
and return a pointer to insure only 1 of the 2 is ever returned.
On point #2, I only slightly favor returning NULL
.
void *
rather thanchar *
. \$\endgroup\$