Count the cost of a row-by-row grid

A function builds a grid of double values with rows = 6 and cols = 50, using one allocation for an array of row pointers and one allocation per row:


C
double **grid = malloc(rows * sizeof *grid);
if (grid == NULL) return NULL;
for (size_t i = 0; i < rows; i++) {
    grid[i] = malloc(cols * sizeof *grid[i]);
    if (grid[i] == NULL) {
        /* release everything obtained so far, then return NULL */
    }
}


On this system sizeof(double) is 8 bytes and sizeof(double *) is 8 bytes. Count requested bytes only, ignoring any allocator overhead; a call that returns NULL reserves nothing. Give each answer as a whole number:

  1. the bytes requested by the row-pointer allocation;
  2. the total bytes requested when every allocation succeeds;
  3. the number of malloc calls made when every allocation succeeds;
  4. in a different run where the allocation for row index 4 returns NULL, the bytes still allocated at that moment;
  5. in that same run, the number of calls to free the cleanup code must make so nothing leaks.
Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Dynamic Memory Questions: