문제

Given the following code snippet:

#include <iostream>
using namespace std;
int *pPointer;

int func()
{
    int num;
    num = 25;
    pPointer = &num;
}

int main()
{
    func();
    cout << *pPointer << endl;
    cout << *pPointer << endl;
    return 0;
}

Can anyone tell me if I duplicate the following line:

cout << *pPointer << endl;
cout << *pPointer << endl;

Why I receive 25 (as expected) but then the next value is 0 (NULL)?

Wouldn't the value of int=25 still remain on the stack? What is it about cout that changes the value of pPointer? Am I missing something about my understanding about scope and the stack? (I'm a Java guy, so this was surprising).

도움이 되었습니까?

해결책

This is because pPointer is pointing to a local variable in func(). This area of memory is only valid inside of the func() method. After func() exits, the memory that pPointer points to is free to be re-used, and appears to be used by cout.

If you want to persist this memory, you should either save it by value, or allocate the memory dynamically pPointer = new int(num)

다른 팁

num does not exist once the function func() terminates.

You take its address when it exists, then attempt to print the value at an address that is no longer valid.

Anything can happen.

As it is undefined behavior, there is no num outside of func scope.

cout << *pPointer << endl;

here *pPointer is pointing to a local variable of some other function which already returned so the address to which it is pointing is out of scope so the behaviour is undefined. it may print the right value assigned to num or may not.

Why I receive 25 (as expected) but then the next value is 0 (NULL)?

What you mention as expected is actually not expected!

num becomes out-of-scope as soon as func() returns. Although pPointer is valid (as it is global), *pPointer is not, because it is pointing to a out-of-scope memory.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top