C Programming Basics
In C, which of the following correctly pairs the lifetimes of (1) a local variable declared inside a function without static, (2) a region allocated with malloc, and (3) a variable declared outside any function?
- A(1) until the program ends, (2) until the function that allocated it returns, (3) until the program ends
- B(1) until execution leaves the block where it is declared, (2) until it is released with free, (3) until the program ends
- C(1) until execution leaves the block where it is declared, (2) until the program ends (it cannot be released earlier), (3) until the function that first used it returns
Show answer and explanation
Answer: B. (1) until execution leaves the block where it is declared, (2) until it is released with free, (3) until the program ends
The automatic variable in (1) is generally placed on the stack; it is created on entry to the block where it is declared and disappears when execution leaves it. The region allocated with malloc in (2) is in the heap; it survives function returns and can be used until it is released with free. The variable outside any function in (3) (and any variable declared static) exists throughout the execution of the program and is placed in a static area such as .data or .bss. Using a pointer to a region whose lifetime has ended, and forgetting free so that regions keep piling up, are common causes of bugs.
- A. An automatic variable disappears when execution leaves its block, and a malloc region survives the function return.
- B. Correct. These are the different lifetimes of automatic, dynamic and static storage.
- C. A malloc region can be released with free at any time, and a variable outside any function exists throughout the execution of the program.