C Programming Basics

int *make(void) {
    int x = 42;
    return &x;
}

Which of the following is true about the pointer returned by the function make above?

  1. Ax stays in the same place until the program ends, so 42 can always be read safely through the returned pointer
  2. Bx is moved to the heap on return, so the caller must free it when finished
  3. CThe lifetime of x ends when the function returns, so the returned pointer points to an invalid location, and using it is undefined behavior
Show answer and explanation

Answer: C. The lifetime of x ends when the function returns, so the returned pointer points to an invalid location, and using it is undefined behavior

x is a local variable without static (an automatic variable); its lifetime ends when the function returns, and the stack location it occupied is reused by other function calls. A pointer that points to a region whose lifetime has ended is called a dangling pointer, and reading or writing through it is undefined behavior. gcc gives a warning for this code and may even generate code that returns NULL. Return the value itself, or use a region prepared by the caller or allocated with malloc.

  • A. An automatic variable's lifetime ends when the function returns, and its location is overwritten by other calls.
  • B. Automatic variables are never moved to the heap.
  • C. Correct. The returned pointer becomes a dangling pointer.
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. In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?
  2. The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?
  3. In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?
  4. 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?
  5. uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?