Skip to content

Instantly share code, notes, and snippets.

@KarlHerler
Last active December 31, 2015 11:59
Show Gist options
  • Save KarlHerler/7983538 to your computer and use it in GitHub Desktop.
Save KarlHerler/7983538 to your computer and use it in GitHub Desktop.
compile using: gcc -ansi megamalloc.c -o megamalloc
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(void) {
int i,size;
int cumulative_mem=0;
int iter=0;
int *base;
clock_t start,end;
size=1000000; /* 1 MB in byte */
srand(time(NULL)); /* random seeding, doesn't have to be very random */
while (1) {
start = clock();
base = (int *)calloc(size, sizeof(int));
end = clock();
if(base != NULL) {
printf("Array of size %d created OK at address %p\n",size,base);
printf("Allocation took %d milliseconds\n", (int)((end-start)*1E3/CLOCKS_PER_SEC));
cumulative_mem++;
printf("Total memory allocated: %d MB\n", cumulative_mem*sizeof(int));
} else {
printf("Not enough memory\n");
printf("Total memory allocated: %d MB\n", cumulative_mem*sizeof(int));
exit(1);
}
start = clock();
int r = rand();
for(i=0;i<size;i++) { base[i] = r; }
end = clock();
printf("Filling the array took %d milliseconds\n", (int)((end-start)*1E3/CLOCKS_PER_SEC));
for(i=0;i<size;i++) {
if (base[i]!=r) {
printf("Expected %d and found %d at %p", r, base[i], base[i]);
exit(1);
}
}
if (iter%4==0) { /* we are intentionally leaking some */
free(base);
cumulative_mem--;
printf("Freeing array of size %d at addr %p", size, base);
}
end = clock();
printf("Array verified OK, took %d milliseconds\n", (int)((end-start)*1E3/CLOCKS_PER_SEC));
iter++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment