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?

  1. A(1) until the program ends, (2) until the function that allocated it returns, (3) until the program ends
  2. B(1) until execution leaves the block where it is declared, (2) until it is released with free, (3) until the program ends
  3. 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.
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. int is 32 bits (maximum 2147483647). Which of the following is the largest n for which the function fact(n) above returns the factorial of n correctly, without overflow?
  2. int is 4 bytes and pointers are 8 bytes. When the value (address) of a pointer to int p is 0x1000, which of the following is the value of p + 3?
  3. int is 4 bytes and pointers are 8 bytes. Which of the following is the output when the program above is executed?
  4. int is 4 bytes. Which of the following is the output when the code above is executed?
  5. Which of the following is the output when the code above, which concerns a char array holding a string, is executed?