OrionLibC
Barry Fixing malloc heap exhaustion bug d0db5bd (2 years, 2 months ago)diff --git a/include/stdlib.h b/include/stdlib.h index b1265c2..7e278b0 100644 --- a/include/stdlib.h +++ b/include/stdlib.h @@ -1,6 +1,8 @@ #ifndef _STDLIB_H #define _STDLIB_H +#include <stddef.h> + #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 @@ -11,12 +13,13 @@ extern "C" { _Noreturn void abort(void); int atexit(void (*)(void)); int atoi(const char *); -void free(void *); +void free(void *addr); char *getenv(const char *); -void *malloc(size_t); +void *malloc(size_t size); void *calloc(size_t, size_t); +void *realloc(void *addr, size_t size); _Noreturn void exit(int status); -int abs(int); +int abs(int num); #ifdef __cplusplus } diff --git a/stdlib/malloc.c b/stdlib/malloc.c index cd19760..2ac9f32 100644 --- a/stdlib/malloc.c +++ b/stdlib/malloc.c @@ -130,7 +130,8 @@ malloc(size_t size) /* Attempt to use arena */ addr = arena_malloc(arena, size); if (!addr && !arena->next) - arena->next = arena_malloc(arena, sizeof(Arena)); + arena->next = arena->start + arena->size + - sizeof(Arena); } return addr; @@ -155,3 +156,20 @@ free(void *addr) if (next) next->prev = prev; } + +/* Re-allocate a region of memory */ +void * +realloc(void *addr, size_t size) +{ + void *ptr = malloc(size); + if (addr) { + Header *old = (Header *) addr - 1; + if (memcmp(old->magic, "HEAP", 4)) { + printf("realloc(): invalid pointer\n"); + abort(); + } + memcpy(ptr, addr, old->size); + free(addr); + } + return ptr; +}