How can potential memory management issues in the following C code be properly solved?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
How can potential memory management issues in the following C code be properly solved?
int* add_numbers(int, int);
void main()
{
int* p;
p = add_numbers(1, 3);
}
int* add_numbers(int a, int b)
{
int* sum = (int*) malloc (16);
*sum = a + b;
return sum;
}
Show answer & explanation
The code exhibits a classic memory leak: add_numbers() allocates memory on the heap with malloc() and returns a pointer to it, but the caller never frees this memory. Option A correctly addresses this by calling free(p) after use. Options B and C don't resolve the leak (function declaration order and static variables are irrelevant to heap deallocation), and Option D avoids the problem but doesn't solve the design—returning heap-allocated pointers is a valid pattern when memory is properly freed.
Step-by-step Derivation:
The issue is a memory leak. The malloc(16) call allocates 16 bytes on the heap. The function returns a pointer to this memory, but main() never deallocates it. Even when the program ends, the OS reclaims it, but in a long-running process, repeated calls would exhaust memory. The fix is to add free(p); after main() is done using p. Option B (function declaration position) has no effect on memory management. Option C (static variables) would actually worsen the issue by persisting the pointer across calls. Option D (avoiding malloc) is impractical for returning dynamically-sized data.