简体   繁体   中英

Manipulate a local static pointer variable outside the function where it is defined

I want to visit and modify a static variable defined in a function in global scope, but the 2nd and the 3rd lines of output are unexpected, why ox is 0?

#include <iostream>

using namespace std;

int * foo(){
    static int *x = new int(5);
    cout << *x << '\t' << &x << endl;
    *x++;
    return x;
}

int main(){
    int * ox;
    ox = foo();
    cout << *ox << '\t' << &ox << endl;
    *ox++;
    cout << *ox << '\t' << &ox << endl;
    int * t= foo();
}

The output is (on my machine):

5   0x6021d0
0   0x7fffdc82d3a0
0   0x7fffdc82d3a0
0   0x6021d0

Any comment is welcomed.

Order of operations. Twice, you perform *ox++; .

This is not evaluated as (*ox)++ "increment the pointed-to value" .

It is *(ox++) "increment the pointer" .

why ox is 0?

ox is pointing to 0 coincidentally. You have incremented it to point to memory that you do not own.

You got caught by some parsing issues. Let's look at the code line-by-line:

static int * x = new int(5);

The first time control flow passes over this line, x is assigned a pointer to a newly allocated int initialized with the value 5. Each following time control flow passes by, the line will be “skipped”. No surprises so far.

cout << *x << '\t' << &x << endl;

I suspect you've meant to print the address of the value, not the pointer, hence typed

cout << *x << '\t' << x << endl;

Now it becomes interesting. This line probably doesn't do what you think it does.

*x++;

The compiler parses this as *(x++) . What is happening is that the pointer x is advanced and its previous value dereferenced and that result thrown away. (Which invokes undefined behavior the next time the function is entered because now x points one past the allocated memory location.) You've probably assumed that it be parsed as (*x)++ which would increment the value pointed-to by x.

The same pattern applies to your main .

If I compile your original code with GCC and pass the -Wall flag (which is always a good idea), it gives us a good hint to what is going on:

main.cpp: In function ‘int* foo()’:
main.cpp:8:7: warning: value computed is not used [-Wunused-value]
   *x++;
       ^

main.cpp: In function ‘int main()’:
main.cpp:16:8: warning: value computed is not used [-Wunused-value]
   *ox++;
        ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM