Last active
December 29, 2015 03:58
-
-
Save Preetam/7611115 to your computer and use it in GitHub Desktop.
This file contains 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> | |
#include <stdint.h> | |
void* mallocAddress = NULL; | |
int | |
look_for_pointer(void* start, void* end, void* address, void* ignore) { | |
if(address == NULL) return 0; | |
int count = 0; | |
void* i; | |
for(i = start; i != end; i+=8) { | |
if( (intptr_t)(*(void**)i) == (intptr_t)(address) && | |
(intptr_t)(i) != (uintptr_t)(ignore) | |
) { | |
count++; | |
} | |
} | |
return count; | |
} | |
void* | |
gc_malloc(int size) { | |
mallocAddress = malloc(size); | |
return mallocAddress; | |
} | |
void | |
GC() { | |
int pointerCount = 0; | |
FILE* fp; | |
char* line = NULL; | |
size_t len = 0; | |
ssize_t read; | |
fp = fopen("/proc/self/maps", "r"); | |
if (fp == NULL) | |
exit(EXIT_FAILURE); | |
while ((read = getline(&line, &len, fp)) != -1) { | |
long start, stop; | |
char read, write; | |
sscanf(line, "%16lx-%16lx %c%c", &start, &stop, &read, &write); | |
if (read == 'r' && write == 'w') { | |
pointerCount += look_for_pointer((void*)start, (void*)stop, mallocAddress, &mallocAddress); | |
} | |
} | |
if (line) | |
free(line); | |
fclose(fp); | |
if (pointerCount == 1) { | |
printf("Freeing %p.\n", mallocAddress); | |
free(mallocAddress); | |
mallocAddress = NULL; | |
} | |
} | |
int | |
main(void) { | |
gc_malloc(10); | |
GC(); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment