Memtrack is a utility that overloads malloc, realloc, and free functions to detect memory leaks.
It does not detect double free, it can only detect memory leaks.
#include <stdio.h>
#include <memtrack.h>
int main(void) {
void *p = malloc(10);
p = realloc(p, 20);
p = realloc(p, 30);
void *q = malloc(20);
q = realloc(q, 40);
q = realloc(q, 60);
memtrack_print_leaks();
return 0;
}Expected output:
memtrack: leak detected, allocated 10 bytes in example.c:5
reallocated to 20 bytes in example.c:6
reallocated to 30 bytes in example.c:7
memtrack: leak detected, allocated 20 bytes in example.c:9
reallocated to 40 bytes in example.c:10
reallocated to 60 bytes in example.c:11
memtrack leak summary:
2 items leaked
90 bytes leaked
#include <stdio.h>
#include "memtrack.h"
int example_init_callback(void *userdata, size_t malloc_count) {
printf("init: malloc_count = %zu\n", malloc_count);
// 0 = success, continue iteration
// non-zero = failure, abort iteration
return 0;
}
int example_malloc_callback(void *userdata, size_t realloc_count, size_t size, const char *file, int line) {
printf("malloc: realloc_count = %zu, size = %zu, %s:%i\n", realloc_count, size, file, line);
return 0;
}
int example_realloc_callback(void *userdata, size_t new_size, const char *file, int line) {
printf("realloc: new_size = %zu, %s:%i\n", new_size, file, line);
return 0;
}
int main() {
void *p = malloc(123);
p = realloc(p, 456);
void *q = malloc(654);
q = realloc(q, 321);
memtrack_iter_info info = {
.userdata = NULL,
.init_callback = example_init_callback,
.malloc_callback = example_malloc_callback,
.realloc_callback = example_realloc_callback
};
memtrack_iter_leaks(&info);
return 0;
}Expected output:
init: malloc_count = 2
malloc: realloc_count = 1, size = 123, example2.c:23
realloc: new_size = 456, example2.c:24
malloc: realloc_count = 1, size = 654, example2.c:26
realloc: new_size = 321, example2.c:27