Created
March 2, 2017 16:16
-
-
Save ralight/4f80e8717a73748dcaf3aecba2348189 to your computer and use it in GitHub Desktop.
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> | |
#define COUNT 100000 | |
#define BLOCKSIZE 1000 | |
int main(int argc, char *argv[]) | |
{ | |
char **ptr; | |
printf("No heap memory has been allocated yet.\n"); | |
printf("Press enter to continue.\n"); | |
getchar(); | |
ptr = malloc(COUNT*sizeof(char *)); | |
if(!ptr){ | |
printf("Out of memory.\n"); | |
return 1; | |
} | |
/* Allocate a load of memory. */ | |
for(int i=0; i<COUNT; i++){ | |
ptr[i] = calloc(BLOCKSIZE, 1); | |
if(!ptr[i]){ | |
printf("Out of memory.\n"); | |
return 1; | |
} | |
} | |
printf("There has now been %ld bytes of heap memory allocated.\n", COUNT*sizeof(char *) + COUNT*BLOCKSIZE); | |
printf("Press enter to continue.\n"); | |
getchar(); | |
/* Free up all of those blocks apart from the last one. */ | |
for(int i=0; i<COUNT-1; i++){ | |
free(ptr[i]); | |
} | |
printf("All but %ld bytes of the heap memory has now been freed.\n", COUNT*sizeof(char *) + BLOCKSIZE); | |
printf("Press enter to continue.\n"); | |
getchar(); | |
free(ptr[COUNT-1]); | |
free(ptr); | |
printf("There should now be no heap memory allocated.\n"); | |
printf("Press enter to continue.\n"); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment