Skip to content

Instantly share code, notes, and snippets.

@opsJson
Last active January 17, 2022 01:24
Show Gist options
  • Save opsJson/c215a30148d4e4d34681485123721b5c to your computer and use it in GitHub Desktop.
Save opsJson/c215a30148d4e4d34681485123721b5c to your computer and use it in GitHub Desktop.
Easily find memory leaks, at runtime.
#include <stdio.h>
#include <stdlib.h>
#ifndef HEAP_MAX
#define HEAP_MAX 50
#endif
struct HeapMap_s {
void *memory;
char *file;
int line;
size_t size;
} HeapMap[HEAP_MAX];
void __HeapLog__() {
int i, count;
for (i=0, count=0; i<HEAP_MAX; i++)
if (HeapMap[i].memory != 0) {
fprintf(stderr, "%lu bytes unallocated at %s:%i\n",
HeapMap[i].size, HeapMap[i].file, HeapMap[i].line);
count++;
}
fprintf(stderr, "Total Leaks: %u\n\n", count);
}
void *__malloc__(size_t size, char *file, int line) {
void *memory;
int i;
for (i=0; i<=HEAP_MAX; i++)
if (HeapMap[i].memory == 0) break;
if (i >= HEAP_MAX) {
fprintf(stderr, "HEAP_MAX of %i bytes rechead!\n", HEAP_MAX);
fprintf(stderr, "Try #define HEAP_MAX [bigger value]");
exit(1);
}
memory = malloc(size);
HeapMap[i].file = file;
HeapMap[i].line = line;
HeapMap[i].size = size;
HeapMap[i].memory = memory;
__HeapLog__();
return memory;
}
void *__calloc__(size_t num, size_t size, char *file, int line) {
void *memory;
int i;
for (i=0; i<=HEAP_MAX; i++)
if (HeapMap[i].memory == 0) break;
if (i >= HEAP_MAX) {
fprintf(stderr, "HEAP_MAX of %i bytes rechead!\n", HEAP_MAX);
fprintf(stderr, "Try #define HEAP_MAX [bigger value]");
exit(1);
}
memory = calloc(num, size);
HeapMap[i].file = file;
HeapMap[i].line = line;
HeapMap[i].size = size;
HeapMap[i].memory = memory;
__HeapLog__();
return memory;
}
void __free__(void *memory) {
int i;
for (i=0; i<=HEAP_MAX; i++)
if (HeapMap[i].memory == memory) {
HeapMap[i].memory = 0;
break;
}
if (i >= HEAP_MAX) return;
free(memory);
__HeapLog__();
}
#define malloc(size) __malloc__(size, __FILE__, __LINE__)
#define calloc(num, size) __calloc__(num, size, __FILE__, __LINE__)
#define free(memory) {__free__(memory); memory = 0;}
/*///////////////////////////////////
Testing:
///////////////////////////////////*/
int main() {
char* a = malloc(sizeof(char) * 2048);
a = malloc(sizeof(char) * 1024);
free(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment