ProgrammingHardProduct company OA

Given this allocation, which code frees everything without leaking or touching freed memory?

Given this allocation, which code frees everything without leaking or touching freed memory?
int **m = malloc(3 * sizeof *m);
for (int i = 0; i < 3; i++) m[i] = malloc((i + 1) * sizeof **m);
  1. A. free(*m); free(m);
  2. B. free(m); for (int i = 0; i < 3; i++) free(m[i]);
  3. C. for (int i = 0; i < 3; i++) free(m[i]); free(m);
  4. D. free(m);

Correct answer: C. for (int i = 0; i < 3; i++) free(m[i]); free(m);

Free the rows first, while m is still valid to read, then the array of row pointers. Freeing m first means m[i] reads freed memory; freeing only m leaks all three rows; free(*m) releases only row 0.

More C Programming questions

Exams that ask this topic