Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the following program, where are i, j and k are stored in memory?

#include <stdio.h>
#include <stdlib.h>
int i;
int main()
{
     int j;
    int *k = (int *) malloc (sizeof(int));
}

 

  • A.i, j and *k are stored in stack segment
  • B.i and j are stored in stack segment. *k is stored on heap.
  • C.i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap.
  • D.j is stored in BSS part of data segment, i is stored in stack segment. *k is stored on heap.

Answer: C

Correct answer: i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap.

Three objects, three regions. i is a global without an initialiser, so it has static storage duration and is zero-initialised; such objects occupy the BSS, which the loader clears rather than reading from the executable.

j is automatic and therefore on the stack. The object k points to came from malloc and lives on the heap. The pointer k itself is automatic and sits on the stack beside j - the pointer and the thing it points to are in different places.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.