diff --git a/libmaxsi/heap.cpp b/libmaxsi/heap.cpp index 5185f580..dc82e81d 100644 --- a/libmaxsi/heap.cpp +++ b/libmaxsi/heap.cpp @@ -229,7 +229,7 @@ namespace Maxsi struct Chunk { public: - size_t size; + size_t size; // Includes size of Chunk and Trailer union { size_t magic; @@ -254,7 +254,7 @@ namespace Maxsi size_t magic; Chunk* prevunused; }; - size_t size; + size_t size; // Includes size of Chunk and Trailer public: bool IsUsed() { return magic == MAGIC; } @@ -262,6 +262,8 @@ namespace Maxsi }; + const size_t OVERHEAD = sizeof(Chunk) + sizeof(Trailer); + // This is how a real chunk actually looks: //struct RealChunk //{ @@ -434,7 +436,7 @@ namespace Maxsi ASSERT(ValidateHeap()); #endif - const size_t OVERHEAD = sizeof(Chunk) + sizeof(Trailer); + // The size field keeps both the allocation and meta information. size += OVERHEAD; // Round up to nearest alignment. @@ -651,6 +653,22 @@ namespace Maxsi Memory::Set(result, 0, total); return result; } + + // TODO: Implement this function properly. + extern "C" void* realloc(void* ptr, size_t size) + { + if ( !ptr ) { return Allocate(size); } + Chunk* chunk = (Chunk*) ((addr_t) ptr - sizeof(Chunk)); + ASSERT(chunk->IsUsed()); + ASSERT(chunk->IsSane()); + size_t allocsize = chunk->size - OVERHEAD; + if ( allocsize < size ) { return ptr; } + void* newptr = Allocate(size); + if ( !newptr ) { return NULL; } + Memory::Copy(newptr, ptr, allocsize); + Free(ptr); + return newptr; + } } } diff --git a/libmaxsi/include/stdlib.h b/libmaxsi/include/stdlib.h index 0c972699..a65b7246 100644 --- a/libmaxsi/include/stdlib.h +++ b/libmaxsi/include/stdlib.h @@ -52,6 +52,7 @@ void _Exit(int status); void free(void*); void* malloc(size_t); int rand(void); +void* realloc(void*, size_t); long strtol(const char* restrict, char** restrict, int); unsigned long strtoul(const char* restrict, char** restrict, int); unsigned long long strtoull(const char* restrict, char** restrict, int); @@ -96,7 +97,6 @@ char* ptsname(int); int putenv(char*); void qsort(void*, size_t, size_t, int (*)(const void*, const void*)); long random(void); -void* realloc(void*, size_t); char* realpath(const char* restrict, char* restrict); unsigned short *seed48(unsigned short [3]); int setenv(const char*, const char*, int);