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?

  1. AWhen fill returns a nonzero value, the function returns without releasing buf, so the allocated region remains unreleased
  2. BThe return value of malloc is not checked, so a null pointer is dereferenced when allocation fails
  3. 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).
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is true about the pointer returned by the function make above?
  2. In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?
  3. The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?
  4. In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?
  5. Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?