why does this function return garbage value

前端 未结 2 1094
梦谈多话
梦谈多话 2020-12-20 09:14

I was writing a program and facing this problem that the following function used to return garbage values:

int* foo(int temp){
   int x = temp;
   return &am         


        
2条回答
  •  独厮守ぢ
    2020-12-20 09:31

    For each function there will be an activation record, which will be created in stack once the execution of that function starts. Activation record holds all the local variables also. And this activation record will be freed once the function execution finishes.

    So if we return an address of a local variable means, that will be freed memory of previous function`s activation record. Dereferencing that memrory is an undefined behaviour.

    In the below case, function foo is returning the &x that means p will holds the address of func's local variable x. This is valid. But if function func tries to retrun p(address of x) which is not valid.

    int* func
    {
       int x;
       int *p;
       ...
       p = foo(&x);
       //using p is valid here
       ...
       return p; //This is invalid
    }
    
    int* foo(int *temp)
    {
       int *x = temp;
       return x //This is valid
    }
    

    In the below case, funciton foo is returning address of its local variable x to function func. So p will holds address of foo's local variable. So deferencing p is invalid because foo functions execution has been completed and its activation record is freed.

    int* func
    {
       int x;
       int *p;
       ...
       p = foo(x);
       //using p is invalid here
       ...
       return p; //This is invalid
    }
    
    int* foo(int temp)
    {
       int x = temp;
       return &x; //This is also invalid
    }
    

提交回复
热议问题