Files
ni-leakdetector/nileakdetector.h

59 lines
1.6 KiB
C
Raw Permalink Normal View History

#pragma once
#include <stdio.h>
#include <stdlib.h>
#ifndef NILEAKDETECTOR_VERBOSE
#define NILEAKDETECTOR_VERBOSE false
#endif
typedef struct _NILeakDetectorData {
size_t n_malloc;
size_t n_free;
} NILeakDetectorData;
static NILeakDetectorData nileakdetector_data = {
.n_malloc = 0,
.n_free = 0
};
// TODO: calloc, realloc
// TODO: pass __FILE__ and __LINE__ so it prints the location of the operations
void *nileakdetector_malloc(size_t block_size) {
void *result = malloc(block_size);
if (result == NULL) {
if(NILEAKDETECTOR_VERBOSE)
printf("[NILeakDetector] Erroneous Allocation (NULL)\n");
} else {
if(NILEAKDETECTOR_VERBOSE)
printf("[NILeakDetector] Allocated %ld Bytes (%p)\n", block_size, result);
nileakdetector_data.n_malloc++;
}
return result;
}
void nileakdetector_free(void *block) {
free(block);
if(NILEAKDETECTOR_VERBOSE)
printf("[NILeakDetector] Freed pointer (%p)\n", block);
nileakdetector_data.n_free++;
}
void nileakdetector_print_summary() {
printf("[NILeakDetector] == SUMMARY ==\n");
printf("[NILeakDetector] Number of mallocs: %ld\n", nileakdetector_data.n_malloc);
printf("[NILeakDetector] Number of frees: %ld\n", nileakdetector_data.n_free);
if (nileakdetector_data.n_malloc != nileakdetector_data.n_free) {
printf("[NILeakDetector] WARNING: POSSIBLE MEMORY LEAKS\n");
}
}
2026-01-15 20:15:05 +02:00
// TODO: nileakdetector_reset -> resets the counting to zero
#undef malloc
#undef free
#define malloc(sz) nileakdetector_malloc(sz)
#define free(p) nileakdetector_free(p)