Вопрос

In the example below:

#include <stdio.h>
#include <stdlib.h>

void test1 (int x)
{
    int * xp = &x;
    printf("Address of xp (test1): [%p]\n", &xp);
    printf("xp points to: [%p] which is the same as [%p]\n", xp, &x);
}

int main()
{
    int x = 4;
    printf("Address of x (main): [%p] \n", &x);
    test1(x);
    return 0;
}

Output:

Address of x (main): [0xbfca0c5c] 
Address of xp (test1): [0xbfca0c2c] 
xp points to: [0xbfca0c40] which is the same as [0xbfca0c40] 
  • What happens to the address 0xbfca0c40 (address of the argument in test1) outside of the function?
  • Where is it located in memory?
Это было полезно?

Решение

That is defined by the implementation.

It's very likely on the machine stack, since the stack is very common way to implement both argument-passing and local variables. The stack space is freed when the test1() function exits, so the memory in question can be re-used.

Другие советы

int x; in the test1 formal parameter list is a variable local to test1. It has similar status to if you also went int y; as a declaration inside test1. It has automatic storage duration.

After test1 exits, the variable no longer exists.

Typically, compilers implement automatic storage via a block of memory that contains a stack structure. When you call a function, new space is claimed on top of the stack for that function's automatic variables (and the return address, and any registers that need to be saved); and when you leave the function, the stack is "popped" back to where it was before you called the function.

  1. The adress will still contain the value of x untill some program will reuse it.
  2. The adress is on the stack, as the variable x is a function argument.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top