Home  >  Q&A  >  body text

c++ - C语言中的堆栈如何分配?

sample code:

int i = 3;
int j;

void f ()
{
    int x = 4;
    int *p = malloc (sizeof(*p));
}

where are i, j, f, x, and p located?

迷茫迷茫2765 days ago639

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:12:09

    Obviously, i and j are used as global variables in the program's static storage area; this area is applied for when the program starts and is not released during the entire program running. .

    x and p are local variables allocated on the call stack . It is allocated when f() is called and released when it returns (pops off the stack).

    fAs a function, the code segment is stored in memory. The code segment is read into memory when the program starts and remains unchanged throughout the program.

    The memory pointed to by

    p is allocated on the heap. The essence of "heap" is the space that the system dynamically allocates to memory - the program treats a section of space dynamically applied for from the system as a "heap" and provides flexible allocation functions such as malloc(). The operating system actually only knows that a section of memory has been requested by the program, but does not know that the usage model of this memory is "heap".

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:12:09

    f:.text segment,
    i:.data segment,
    j:.bss segment,
    x,p:stack,
    x and p are local variables, stored on the stack on, but the memory space pointed to by p is on the heap.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:12:09

    i,j are in the static area, x is in the stack area, and the content of p is in the heap area

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:12:09

    sampe—>sample is->are

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:12:09

    Please read the following two articles, it will be explained very clearly

    ij is in the heap
    xp is in the stack

    http://segmentfault.com/a/1190000002575242

    http://m.blog.csdn.net/blog/zhoucoolqi/7540612

    reply
    0
  • Cancelreply