void * realloc(void * pointer, size_t size) { void * (* libc_realloc)(void *, size_t) = (void *(*)(void *, size_t))dlsym(RTLD_NEXT, "realloc"); if (enabled.load()) { return custom_realloc(pointer, size); } return libc_realloc(pointer, size); }
TEST_F(MallocTests, GrowingRealloc) { void *ptr = NULL; size_t sz = 16; for (uint64_t i = 0; i < 512; i++) { ptr = custom_realloc(ptr, sz * i); ASSERT_NE(ptr, (void *) NULL); memset(ptr, 0, sz * i); } }
TEST_F(MallocTests, ManyReallocs) { char* ptr = NULL; char* new_ptr = NULL; size_t sz = 16; size_t max_sz = 1024; ptr = (char*) custom_malloc(sizeof(char) * 16); memset(ptr, 'A', 16); for (uint64_t i = 1; i <= max_sz - sz; i++) { new_ptr = (char*) custom_realloc(ptr, sz + i); ASSERT_NE(new_ptr, (void*) NULL); memset(new_ptr, 'A', sz + i); ptr = new_ptr; } ASSERT_EQ(custom_malloc_usable_size(ptr), max_sz); custom_free(ptr); }
/* The realloc to be used for data returned by the public API. */ void * _gpgrt_realloc (void *a, size_t n) { if (custom_realloc) return custom_realloc (a, n); if (!n) { free (a); return NULL; } if (!a) return malloc (n); return realloc (a, n); }
TEST_F(MallocTests, ZeroRealloc) { void *ptr = NULL; ptr = custom_realloc(NULL, 0); ASSERT_NE(ptr, (void *) NULL); ASSERT_GE(custom_malloc_usable_size(ptr), static_cast<size_t>(0)); }