Pointer to local variable in C++

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

I have the following code in C++

int* foo()
{
    int myVar = 4;
    int* ptr = &myVar;
    return ptr;
}

int main()
{
   printf("val= %d", *foo());
   return 0;
}

The output i get is:

val = 4

So my question is since myVar is a local variable, shouldn't it be gone after the function returns? and shouldn't the pointer to it be a null pointer as well?


So my question is since myVar is a local variable, should it be gone after the function returns?

Yes. It would point to the address you set it to. However, the region was local to the function. Assume it does not belong to you after what it points to goes out of scope.

It is as incorrect as:

uint8_t* p = (uint8_t*)malloc(count);
free(p);
p[0] = 1;

but far more difficult an error for your or your tools to diagnose because the region would exist on the stack (unless optimized away).

and shouldn't the pointer to it be a null pointer as well?

No. C and C++ don't manage this for you.


In your case, printf("val= %d", *foo()) is printing the garbage value. As there is no other code, that data has not been changed.

You run this code, you will get the idea

    int* foo() 
    { 
        int myVar = 4; 
        int* ptr = &myVar; 
        return ptr; 
    } 

    int* foo1() 
    { 
        int myVar = 5; 
        int* ptr = &myVar; 
        return ptr; 
    } 
    int main() 
    { 
        int* x = foo();
        int* x1 = foo1();
       printf("val= %d", *x); 
       return 0; 
    } 

The address at ptr* will remain allocated and if you call function again, it will change the pointer. At least that would be my theory. C++ will not overwrite your pointer for performance reasons.

int foo(int val) {
  int myVar = val;
  int* ptr = &myVar;
  return ptr; 
}

int main()
{
   int *ptr = foo(4);
   foo(3);
   printf("val= %d", *ptr); //will print 3
   return 0;
}
链接地址: http://www.djcxy.com/p/36336.html

上一篇: C中局部变量的内存分配

下一篇: 指向C ++中的局部变量