Last active
January 15, 2022 02:15
-
-
Save opsJson/18c6d477c2096142c44e505d7afe949d to your computer and use it in GitHub Desktop.
every time malloc/calloc is called again, the memory is automatically freed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#ifndef HEAP_MAX | |
#define HEAP_MAX 1 | |
#endif | |
struct HeapMap_s { | |
void *memory; | |
char *file; | |
int line; | |
} HeapMap[HEAP_MAX]; | |
size_t HeapCount = 0; | |
void *__malloc__(size_t size, char *file, int line) { | |
void *memory; | |
int i, index; | |
for (i=0; i<=HeapCount; i++) | |
if (HeapMap[i].file == file && HeapMap[i].line == line) { | |
free(HeapMap[i].memory); | |
break; | |
} | |
if (i >= HeapCount) index = HeapCount++; | |
else index = i; | |
if (HeapCount > HEAP_MAX) { | |
fprintf(stderr, "Heap Max Rechead!\n"); | |
fprintf(stderr, "Try #define HEAP_MAX [bigger value]\n"); | |
exit(1); | |
} | |
memory = malloc(size); | |
HeapMap[index].file = file; | |
HeapMap[index].line = line; | |
HeapMap[index].memory = memory; | |
return memory; | |
} | |
void *__calloc__(size_t num, size_t size, char *file, int line) { | |
void *memory; | |
int i, index; | |
for (i=0; i<=HeapCount; i++) | |
if (HeapMap[i].file == file && HeapMap[i].line == line) { | |
free(HeapMap[i].memory); | |
break; | |
} | |
if (i >= HeapCount) index = HeapCount++; | |
else index = i; | |
memory = calloc(num, size); | |
HeapMap[index].file = file; | |
HeapMap[index].line = line; | |
HeapMap[index].memory = memory; | |
return memory; | |
} | |
void __free__() { | |
//free is not needed | |
} | |
#define malloc(size) __malloc__(size, __FILE__, __LINE__) | |
#define calloc(num, size) __calloc__(num, size, __FILE__, __LINE__) | |
#define free(memory) __free__() | |
int main() { | |
while (1) { | |
char *c = malloc(2048); //check system monitor for no leaks | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment