commit 793139462e5134659ff54b99af7116be2e6e4dfc
parent d3d88235076197305a01e6460f43ea302b8809d1
Author: Robert Russell <robertrussell.72001@gmail.com>
Date: Thu, 2 Feb 2023 19:52:09 -0800
Make sure non-e allocators set errno to ENOMEM
Apparently, malloc, calloc, and realloc are not required to touch
errno, so we must do it ourselves.
Diffstat:
2 files changed, 17 insertions(+), 7 deletions(-)
diff --git a/inc/rcx/alloc.h b/inc/rcx/alloc.h
@@ -7,7 +7,8 @@
* re- => realloc-style allocator
* -n => array allocator (with overflow check)
* -z => new memory initialized to 0.
- * All these allocators are interoperable with the stdlib allocators. */
+ * All these allocators are interoperable with the stdlib allocators. The
+ * non-e variants all set errno to ENOMEM on failure. */
void *r_alloc(usize size); /* aka malloc */
void *r_allocz(usize size);
void *r_allocn(usize len, usize size);
diff --git a/src/alloc.c b/src/alloc.c
@@ -10,12 +10,16 @@
void *
r_alloc(usize size) {
- return malloc(size);
+ void *p = malloc(size);
+ if (!p) errno = ENOMEM;
+ return p;
}
void *
r_allocz(usize size) {
- return calloc(1, size);
+ void *p = calloc(1, size);
+ if (!p) errno = ENOMEM;
+ return p;
}
void *
@@ -29,14 +33,19 @@ r_allocn(usize len, usize size) {
void *
r_allocnz(usize len, usize size) {
- return calloc(len, size);
+ void *p = calloc(len, size);
+ if (!p) errno = ENOMEM;
+ return p;
}
int
r_realloc(void *p, usize size) {
- void *q = realloc(*(void**)p, size);
- if (!q) return -1;
- *(void**)p = q;
+ void *q = realloc(*(void **)p, size);
+ if (!q) {
+ errno = ENOMEM;
+ return -1;
+ }
+ *(void **)p = q;
return 0;
}