Skip to content

Commit c01d0c6

Browse files
authored
Merge pull request #98 from devnexen/reallocarray
reallocarray interface.
2 parents bcd1a38 + 4f8247f commit c01d0c6

4 files changed

Lines changed: 30 additions & 0 deletions

File tree

include/iso_alloc.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ extern "C" {
3333
EXTERNAL_API NO_DISCARD MALLOC_ATTR ALLOC_SIZE ASSUME_ALIGNED void *iso_alloc(size_t size);
3434
EXTERNAL_API NO_DISCARD MALLOC_ATTR CALLOC_SIZE ASSUME_ALIGNED void *iso_calloc(size_t nmemb, size_t size);
3535
EXTERNAL_API NO_DISCARD MALLOC_ATTR REALLOC_SIZE ASSUME_ALIGNED void *iso_realloc(void *p, size_t size);
36+
EXTERNAL_API NO_DISCARD MALLOC_ATTR REALLOC_SIZE ASSUME_ALIGNED void *iso_reallocarray(void *p, size_t nmemb, size_t size);
3637
EXTERNAL_API void iso_free(void *p);
3738
EXTERNAL_API void iso_free_size(void *p, size_t size);
3839
EXTERNAL_API void iso_free_permanently(void *p);

src/iso_alloc_interfaces.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,16 @@ EXTERNAL_API NO_DISCARD REALLOC_SIZE ASSUME_ALIGNED void *iso_realloc(void *p, s
6969
return r;
7070
}
7171

72+
EXTERNAL_API NO_DISCARD MALLOC_ATTR REALLOC_SIZE ASSUME_ALIGNED void *iso_reallocarray(void *p, size_t nmemb, size_t size) {
73+
unsigned int res;
74+
75+
if(__builtin_umul_overflow(nmemb, size, &res)) {
76+
return NULL;
77+
}
78+
79+
return iso_realloc(p, nmemb * size);
80+
}
81+
7282
EXTERNAL_API NO_DISCARD ASSUME_ALIGNED char *iso_strdup(const char *str) {
7383
return iso_strdup_from_zone(NULL, str);
7484
}

src/malloc_hook.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,14 @@ EXTERNAL_API void *realloc(void *p, size_t s) {
4545
return iso_realloc(p, s);
4646
}
4747

48+
EXTERNAL_API void *__libc_reallocarray(void *p, size_t n, size_t s) {
49+
return iso_reallocarray(p, n, s);
50+
}
51+
52+
EXTERNAL_API void *reallocarray(void *p, size_t n, size_t s) {
53+
return iso_reallocarray(p, n, s);
54+
}
55+
4856
EXTERNAL_API int __posix_memalign(void **r, size_t a, size_t s) {
4957
/* All iso_alloc allocations are 8 byte aligned */
5058
*r = iso_alloc(s);

tests/interfaces_test.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,17 @@ int main(int argc, char *argv[]) {
3838
LOG_AND_ABORT("iso_realloc failed")
3939
}
4040

41+
/* Test iso_reallocarray */
42+
if(iso_reallocarray(NULL, SIZE_MAX, SIZE_MAX) != NULL) {
43+
LOG_AND_ABORT("iso_reallocarray should have overflown");
44+
}
45+
46+
p = iso_reallocarray(p, 16, 16);
47+
48+
if(p == NULL) {
49+
LOG_AND_ABORT("iso_reallocarray failed")
50+
}
51+
4152
iso_free(p);
4253

4354
p = iso_alloc(1024);

0 commit comments

Comments
 (0)