/******************************************************************************\ Run some test to see if memory checking actually works. Note that code here is intentionally poor, so do not fix "bugs" here they are there for a reason. \******************************************************************************/ void C_test_mem_check(void) { char *ptr; int i; switch (c_mem_check.value.n) { case 0: case 1: return; case 2: C_debug("Normal operation, shouldn't fail"); ptr = C_malloc(1024); C_free(ptr); ptr = C_calloc(1024); C_realloc(ptr, 2048); C_realloc(ptr, 512); C_free(ptr); return; case 3: C_debug("Intentionally leaking memory"); ptr = C_malloc(1024); return; case 4: C_debug("Freeing unallocated memory"); C_free((void *)0x12345678); break; case 5: C_debug("Double freeing memory"); ptr = C_malloc(1024); C_free(ptr); C_free(ptr); break; case 6: C_debug("Simulating memory underrun"); ptr = C_malloc(1024); for (i = 0; i > -NO_MANS_LAND_SIZE / 2; i--) ptr[i] = 42; C_free(ptr); break; case 7: C_debug("Simulating memory overrun"); ptr = C_malloc(1024); for (i = 1024; i < 1024 + NO_MANS_LAND_SIZE / 2; i++) ptr[i] = 42; C_free(ptr); break; case 8: C_debug("Reallocating unallocated memory"); ptr = C_realloc((void *)0x12345678, 1024); break; case 9: C_debug("Intentionally leaking string"); ptr = C_malloc(1024); C_strncpy(ptr, "This string was leaked", 1024); return; default: C_error("Unknown memory check test %d", c_mem_check.value.n); } C_error("Memory check test %d failed", c_mem_check.value.n); }
/******************************************************************************\ Realloc so the array isn't overallocated, and return the pointer to the dynamic memory, otherwise cleaning up. \******************************************************************************/ void *C_array_steal(c_array_t *array) { void *result; result = C_realloc(array->data, array->len * array->item_size); C_zero(array); return result; }
// Re-allocates a list. Count may be zero. virtual ListType *Realloc(CountType in_count, const char *name_string = NULL) { MLB::Utility::CheckCountTypeAndValue(in_count, name_string); if (!in_count) Free(); else if (!the_count_) Calloc(in_count, name_string); else if (in_count > the_count_) { ListType *tmp_list; tmp_list = reinterpret_cast<ListType *>( C_realloc(the_list_, in_count * sizeof(ListType), name_string)); if (in_count > the_count_) memset(reinterpret_cast<char *>(tmp_list) + (sizeof(ListType) * the_count_), '\0', (in_count - the_count_) * sizeof(ListType)); the_count_ = in_count; the_list_ = tmp_list; } return(the_list_); }
/******************************************************************************\ Ensure that enough space is allocated for [n] elements. \******************************************************************************/ void C_array_reserve(c_array_t *array, int n) { array->data = C_realloc(array->data, array->item_size * n); array->capacity = n; }