Created
October 15, 2013 05:25
-
-
Save peterdemin/6986910 to your computer and use it in GitHub Desktop.
Slightly rewritten test from http://bugs.python.org/issue19246 that demonstrates memory fragmentation issue.
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 <assert.h> | |
int create_huge_linked_list(void **last_item) { | |
int i; | |
void *prev_item = NULL; | |
for(i = sizeof(void *); i < 1000000; i++) { | |
void *new_item = malloc(i); | |
if(new_item == NULL) { | |
break; | |
} | |
*(void **)new_item = prev_item; | |
prev_item = new_item; | |
} | |
*last_item = prev_item; | |
return i; | |
} | |
void free_linked_list(void *last_item) { | |
while(last_item != NULL) { | |
void *prev_item = *(void **)last_item; | |
free(last_item); | |
last_item = prev_item; | |
} | |
} | |
int stress_heap() { | |
void *last_item; | |
int amount = create_huge_linked_list(&last_item); | |
free_linked_list(last_item); | |
return amount; | |
} | |
void stress_twice(void) { | |
int first = stress_heap(); | |
int second = stress_heap(); | |
printf("%i %i %f%%\n", first, second, 100.0 * second / first); | |
} | |
void stress_and_alloc_1_mb() { | |
void *ptr; | |
ptr = malloc(1000000); | |
if(ptr != NULL) { | |
printf("Successfully allocated 1 MB before stress\n"); | |
free(ptr); | |
stress_heap(); | |
ptr = malloc(1000000); | |
if(ptr != NULL) { | |
printf("Successfully allocated 1 MB after stress\n"); | |
free(ptr); | |
} else { | |
printf("Failed to allocate 1 MB after stress\n"); | |
} | |
} else { | |
printf("Failed to allocate 1 MB before stress\n"); | |
} | |
} | |
int main() { | |
stress_and_alloc_1_mb(); | |
stress_twice(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment