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?
- Ax stays in the same place until the program ends, so 42 can always be read safely through the returned pointer
- Bx is moved to the heap on return, so the caller must free it when finished
- 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.