fork download
  1. #include <stdio.h>
  2. #include <stddef.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #include <assert.h>
  6.  
  7. #define allocate( type, n ) malloc( sizeof(type) * n )
  8. #define clear_allocate( type, n ) calloc( n, sizeof(type) )
  9.  
  10. // total rows initialized in pool
  11. #define NUM_ROWS (size_t)100
  12.  
  13. #define HEIGHT (size_t)3
  14. #define WIDTH (size_t)4
  15.  
  16. int main() {
  17.  
  18. typedef double Element;
  19. typedef Element* Row;
  20. typedef Row* Matrix;
  21.  
  22. _Bool allocate_successfully = true;
  23. size_t failure_at = NUM_ROWS;
  24.  
  25. // handle of all rows
  26. Row * allocated_rows = allocate( Row, NUM_ROWS );
  27. assert( allocated_rows != NULL ); // fatal error
  28. // init each rows ( allocate memory needed )
  29. for ( size_t i = 0; allocate_successfully && i != NUM_ROWS; ++i ) {
  30.  
  31. allocated_rows[ i ] = allocate( Element, WIDTH );
  32.  
  33. if ( allocated_rows[ i ] == NULL ) {
  34. allocate_successfully = false;
  35. failure_at = i;
  36. }
  37. }
  38.  
  39. if ( allocate_successfully == false )
  40. goto after_use;
  41.  
  42. size_t next = 0;
  43. Matrix a1 = allocate( Row, HEIGHT );
  44. assert( a1 != NULL ); // fatal error
  45. for ( size_t row = 0; row != HEIGHT; ++row ) {
  46. a1[ row ] = allocated_rows[ next++ ];
  47. }
  48.  
  49. Matrix a2 = allocate( Row, HEIGHT );
  50. assert( a2 != NULL ); // fatal error
  51. for ( size_t row = 0; row != HEIGHT; ++row ) {
  52. a2[ row ] = allocated_rows[ next++ ];
  53. }
  54.  
  55. after_use:
  56. {
  57. Matrix matrices[] = { a1, a2 };
  58. for ( size_t i = 0; i != sizeof(matrices)/sizeof(matrices[0]); ++i )
  59. free( matrices[ i ] );
  60.  
  61. // free the rows allocated in pool
  62. for ( size_t i = 0; i != failure_at; ++i )
  63. free( allocated_rows[ i ] );
  64. free( allocated_rows );
  65. }
  66.  
  67. return EXIT_SUCCESS;
  68. }
Success #stdin #stdout 0.02s 1848KB
stdin
Standard input is empty
stdout
Standard output is empty