Consider the following C code:
#include<stdio.h>
int *assignval (int *x, int val) {
*x = val;
return x;
}
void main () {
int *x = malloc(sizeof(int));
if (NULL == x) return;
x = assignval (x,0);
if (x) {
x = (int *)malloc(sizeof(int));
if (NULL == x) return;
x = assignval (x,10);
}
printf("%d\n", *x);
free(x);
}
The code suffers from which one of the following problems:
View worked solution
Answer: D
To analyze the behavior of the given C code, let us trace its execution step-by-step:
- First Allocation:
int *x = malloc(sizeof(int));
A block of memory (let's call it ) is allocated on the heap, and its address is stored in the pointer variablex. - Assignment:
x = assignval(x, 0);
The value at is set to0, andxcontinues to point to . - Second Allocation (Inside
if (x)block):x = (int *)malloc(sizeof(int));
A new block of memory (let's call it ) is allocated on the heap, and its address is assigned tox.
At this point, the address of the first block is overwritten and lost. Since there is no other pointer referencing , this memory block can never be accessed or freed. This is a classic memory leak. - Deallocation:
free(x);
Only the second block is freed. The first block remains allocated in the heap until the program terminates.
Evaluating the Options:
- Option A is incorrect: In C,
mallocreturns avoid*which is implicitly converted to any pointer type (likeint*). No explicit typecasting is required, so there is no compiler error. - Option B is incorrect: The comparison
NULL == x(often called a Yoda condition) is perfectly valid in C and prevents accidental assignment (e.g., writingx = NULLinstead ofx == NULL). - Option C is incorrect: A dangling pointer is a pointer that points to a memory location that has already been deallocated. Here,
xis freed at the very end of the function, and is not dereferenced after being freed. - Option D is correct: The code compiles successfully, but the loss of the reference to the first allocated block results in a memory leak.
Free practice · Your answers on this page are not saved.
