dluciv

Does free() really free memory pages of fragmented heap

May 29th, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. #define QUANTITY 512
  6. // Piece size
  7. #define PIECE (1024*1024)
  8.  
  9. void *pieces[QUANTITY];
  10.  
  11. void allocate()
  12. {
  13.     for(size_t i = 0; i < QUANTITY; ++i)
  14.     {
  15.         pieces[i] = malloc(PIECE);
  16.         memset(pieces[i], 0xff, PIECE);
  17.     }
  18. }
  19.  
  20. void fragment()
  21. {
  22.     for(size_t i = 0; i < QUANTITY; i+=2)
  23.     {
  24.         free(pieces[i]);
  25.         pieces[i] = NULL;
  26.     }
  27. }
  28.  
  29. void deallocate()
  30. {
  31.     for(size_t i = 0; i < QUANTITY; ++i)
  32.         free(pieces[i]);
  33. }
  34.  
  35. int main()
  36. {
  37.     // Allocate, fragment and deallocate memory and see
  38.     // if system virtual memory is really freed by deallocation
  39.     for(;;)
  40.     {
  41.         allocate();
  42.         puts("Allocated");
  43.         getchar();
  44.         fragment();
  45.         puts("Fragmented");
  46.         getchar();
  47.         deallocate();
  48.         puts("Deallocated");
  49.         getchar();
  50.     }
  51.     return 0;
  52. }
Add Comment
Please, Sign In to add comment