Skip to content

Instantly share code, notes, and snippets.

@ben0x539
Created March 18, 2012 18:39
Show Gist options
  • Save ben0x539/2079513 to your computer and use it in GitHub Desktop.
Save ben0x539/2079513 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
size_t check_malloc_size(void* p, size_t n) {
int fd[2];
pid_t child;
pipe(fd);
child = fork();
if (child == 0) {
void* orig;
void* dummy;
dummy = malloc(1);
for (orig = p; orig == p; p = realloc(p, ++n))
;
free(dummy);
write(fd[1], &n, sizeof(n));
exit(EXIT_SUCCESS);
} else {
int status;
read(fd[0], &n, sizeof(n));
waitpid(child, &status, 0);
return n - 1;
}
assert(0);
}
int main(void) {
void* p;
unsigned n;
for (;;) {
if (scanf("%u", &n) != 1)
break;
p = malloc(n);
printf("%u\n", (unsigned) check_malloc_size(p, n));
free(p);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment