RicardasSim

free();

Aug 10th, 2020
1,911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <stdint.h>
  6. #include <stdbool.h>
  7.  
  8. #define TEST_SIZE 1000000
  9.  
  10. int32_t *p1;
  11. int32_t *p2;
  12. int32_t *p3;
  13.  
  14. void cleanup()
  15. {
  16.  
  17.     free(p1);
  18.     free(p2);
  19.     free(p3);
  20.  
  21. }
  22.  
  23. int main()
  24. {
  25.  
  26.     int32_t *p_loc_1;
  27.     int32_t *p_loc_2;
  28.     int32_t *p_loc_3;  
  29.  
  30.     p_loc_1 = malloc( TEST_SIZE * sizeof *p_loc_1 );
  31.     p_loc_2 = malloc( TEST_SIZE * sizeof *p_loc_2 );
  32.     p_loc_3 = malloc( TEST_SIZE * sizeof *p_loc_3 );
  33.  
  34.     if ( !p_loc_1 || !p_loc_2 || !p_loc_3 )
  35.     {
  36.         printf( "Error: cannot allocate memory (1).\n" );
  37.        
  38.         free( p_loc_1 );
  39.         free( p_loc_2 );
  40.         free( p_loc_3 );
  41.  
  42.         return 1;
  43.     }
  44.  
  45.     // ... code ...
  46.  
  47.     free( p_loc_1 );
  48.     free( p_loc_2 );
  49.     free( p_loc_3 );
  50.  
  51.     /**************************************************************/
  52.  
  53.     p1 = malloc( TEST_SIZE * sizeof *p1 );
  54.     p2 = malloc( TEST_SIZE * sizeof *p2 );
  55.     p3 = malloc( TEST_SIZE * sizeof *p3 );
  56.  
  57.     if ( !p1 || !p2 || !p3 )
  58.     {
  59.         printf( "Error: cannot allocate memory (2).\n" );
  60.        
  61.         cleanup();
  62.  
  63.         return 1;
  64.     }
  65.  
  66.     // ... code ...
  67.  
  68.     cleanup();
  69.  
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment