Carp/core/carp_memory.h

89 lines
2.1 KiB
C
Raw Normal View History

2018-02-27 16:14:14 +03:00
#ifdef LOG_MEMORY
Long malloc_balance_counter = 0;
2018-02-27 16:14:14 +03:00
bool log_memory_balance = false;
void *logged_malloc(size_t size) {
void *ptr = malloc(size);
if (log_memory_balance) {
2020-04-23 11:42:35 +03:00
printf("MALLOC: %p (%zu bytes)\n", ptr, size);
}
2018-02-27 16:14:14 +03:00
malloc_balance_counter++;
return ptr;
}
void logged_free(void *ptr) {
if (log_memory_balance) {
printf("FREE: %p\n", ptr);
}
2018-02-27 16:14:14 +03:00
free(ptr);
malloc_balance_counter--;
/* if(malloc_balance_counter == 0) { */
/* printf("malloc is balanced! (this should be the last thing you
* see)\n"); */
2018-02-27 16:14:14 +03:00
/* } */
/* else if(malloc_balance_counter < 0) { */
/* printf("malloc is %ld, that is bad!\n", malloc_balance_counter); */
/* } */
}
void Debug_log_MINUS_memory_MINUS_balance_BANG_(bool value) {
log_memory_balance = value;
}
#define CARP_MALLOC(size) logged_malloc(size)
#define CARP_FREE(ptr) logged_free(ptr)
#define CARP_REALLOC(ptr, size) realloc(ptr, size)
2018-02-27 16:14:14 +03:00
Long Debug_memory_MINUS_balance() {
return malloc_balance_counter;
}
2018-02-27 16:14:14 +03:00
void Debug_reset_MINUS_memory_MINUS_balance_BANG_() {
malloc_balance_counter = 0;
}
#else
2019-06-17 10:17:20 +03:00
#ifdef CHECK_ALLOCATIONS
void* CARP_MALLOC(size_t size) {
void* res = malloc(size);
if (!res) abort();
return res;
2019-06-17 10:17:20 +03:00
}
void* CARP_REALLOC(void* ptr, size_t size) {
void* res = realloc(ptr, size);
if (!res) abort();
return res;
}
2019-06-17 10:17:20 +03:00
#else
2018-02-27 16:14:14 +03:00
#define CARP_MALLOC(size) malloc(size)
#define CARP_REALLOC(ptr, size) realloc(ptr, size)
2019-06-17 10:17:20 +03:00
#endif
2018-02-27 16:14:14 +03:00
#define CARP_FREE(ptr) free(ptr)
Long Debug_memory_MINUS_balance() {
printf(
"Error - calling 'memory-balance' without compiling with LOG_MEMORY "
"enabled (--log-memory).\n");
2018-02-27 16:14:14 +03:00
exit(1);
return 0;
}
void Debug_reset_MINUS_memory_MINUS_balance_BANG_() {
printf(
"Error - calling 'reset-memory-balance!' without compiling with "
"LOG_MEMORY enabled (--log-memory).\n");
2018-02-27 16:14:14 +03:00
exit(1);
}
void Debug_log_MINUS_memory_MINUS_balance_BANG_(bool value) {
printf(
"Error - calling 'log-memory-balance!' without compiling with "
"LOG_MEMORY enabled (--log-memory).\n");
2018-02-27 16:14:14 +03:00
exit(1);
}
#endif