ProgrammingHardProduct company OA
What is wrong with this code?
What is wrong with this code?
char *p = malloc(10); p++; free(p);
- A. free must be given exactly the pointer malloc returned; passing p + 1 is undefined behaviour
- B. free needs the size of the block as a second argument
- C. It only leaks one byte
- D. Nothing: free releases the whole block containing p
Correct answer: A. free must be given exactly the pointer malloc returned; passing p + 1 is undefined behaviour
The allocator finds a block's bookkeeping from the exact address it handed out; any other pointer, even one inside the block, makes free undefined (often a crash or heap corruption). Keep the original pointer, or move a separate pointer.
More C Programming questions
- What is printed? c int x = 5; #define x (x + 1) printf("%d", x);
- What is printed? c int c = 0; for (int i = 1; i <= 16; i = 2) for (int j = 0; j < i; j++) c++; printf("%d", c);
- What is printed? c int i, c = 0; for (i = 0; i < 10; i += i + 1) c++; printf("%d %d", c, i);
- What is printed? c int a = 2, b = 4; printf("%d %d %d", a & b, a && b, a | b);
- What is printed? c int z(int n) { return n < 5 ? 0 : n / 5 + z(n / 5); } int main(void) { printf("%d %d", z(100), z(125)); }
- What is printed? c int next(void) { static int n; return n += 2; } int prev(void) { static int n = 10; return n -= 3; } int main(void) {…