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);
- A. free(*m); free(m);
- B. free(m); for (int i = 0; i < 3; i++) free(m[i]);
- C. for (int i = 0; i < 3; i++) free(m[i]); free(m);
- 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
- With char a = "hi", b = "hi"; what can be said about the value of a == b?
- What is printed? c int c = 0; for (int i = 1; i <= 4; i++) for (int j = i; j <= 4; j += i) c++; printf("%d", c);
- Assume 16-bit unsigned short and 32-bit int. What is printed? c unsigned short v = 0x1234; unsigned short w = (unsigned short)(v << 8 | v…
- What is printed? c void conv(int n, int b) { if (n >= b) conv(n / b, b); putchar("0123456789ABCDEF"[n % b]); } int main(void) { conv(255…
- A single C source file contains these three lines at file scope. What happens? c int x; int x; int x = 5;
- Assume 4-byte int, 8-byte double and natural alignment. What is printed? c struct T { double d; int i; }; struct T arr[3]; printf("%td"…