C Programming Basics
int process(int n) {
int *buf = malloc(n * sizeof(int));
if (buf == NULL) return -1;
if (fill(buf, n) != 0)
return -2;
use(buf, n);
free(buf);
return 0;
}fill and use are functions defined elsewhere. Which of the following is a problem with the function above?
- AWhen fill returns a nonzero value, the function returns without releasing buf, so the allocated region remains unreleased
- BThe return value of malloc is not checked, so a null pointer is dereferenced when allocation fails
- Cbuf is used after free, so a released region is accessed
Show answer and explanation
Answer: A. When fill returns a nonzero value, the function returns without releasing buf, so the allocated region remains unreleased
A region allocated with malloc remains until it is released with free. On the path where fill fails and the function returns with return -2, free is not called and the value (address) of buf is lost, so that region can never be released. This is called a memory leak; when the function is called repeatedly the usable memory keeps shrinking, which is a particular problem for embedded devices and servers that run for a long time. Call free(buf) before returning, or gather the release into one place at the end of the function.
- A. Correct. free is not called on the error return path, causing a memory leak.
- B. buf == NULL is checked right after malloc, and -1 is returned on failure.
- C. buf is not used after free(buf).