Skip to content

Commit 47de5a0

Browse files
Nicolas Pitrenashif
authored andcommitted
libc/minimal: fix realloc() failure case
It is said that the C17 realloc() behavior is to return the original pointer on error and that's what is implemented here. This may be confused with a successful realloc() and nobody else does that. Instead, a failed realloc() should return NULL, leave the original memory intact and set errno to ENOMEM. This is the behavior described by all the following references: Linux/glibc: https://man7.org/linux/man-pages/man3/malloc.3.html NetBSD https://man.netbsd.org/realloc.3 Microsoft https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/realloc Mac OS X https://developer.apple.com/library/archive/documentation/System/\ Conceptual/ManPages_iPhoneOS/man3/reallocf.3.html Open Group Base Specifications Issue 6 https://pubs.opengroup.org/onlinepubs/009604599/functions/realloc.html PTC MKS Toolkit https://www.mkssoftware.com/docs/man3/realloc.3.asp Let's get in line with the most common behavior. Signed-off-by: Nicolas Pitre <[email protected]>
1 parent 5939970 commit 47de5a0

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

lib/libc/minimal/source/stdlib/malloc.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,10 @@ void *realloc(void *ptr, size_t requested_size)
6060
__alignof__(z_max_align_t),
6161
requested_size);
6262

63-
return ret == NULL ? ptr : ret;
63+
if (ret == NULL && requested_size != 0) {
64+
errno = ENOMEM;
65+
}
66+
return ret;
6467
}
6568

6669
void free(void *ptr)

0 commit comments

Comments
 (0)