简体   繁体   中英

Scope a variable on stack in c++

Hi there i am new in c++ and my question is related to scope of a variable. Let me ask the quesion considering the code below

#include <iostream>

static int* fun(){
  static int *ptr = new int(4);
  return ptr;
}

 static int * tun() noexcept{
   int f = 111;
   *(fun()) = f;
   return fun();
 }

 static int *sun(){
  return tun();
}

int main() {
  std::cout << (*sun()) << std::endl;
}

In the middle function tun() there is a variable named f and when the function return it is poped from the stack as per my knowledge. in this case the function return to sun() which is then called in main() and inside main it is giving me correct value of the variable decleard and initialized in function tun() . Can anybody explain this behaviour to me, i am a bit confused on it.

The variable f is gone, but its value has been stored in the int that the pointer returned by fun points to. The code can be simplified to

#include <iostream>

int * tun() {
   static int* ptr = new int;
   int f = 111;
   *ptr = f;                  // copy value of f
   return ptr;                  
}                             // f is gone now, but who cares?


int main() {
  std::cout << (*tun()) << std::endl;
}

Its not clear what the code is supposed to do other than obfuscation, btw.

tun() returns a pointer that is pointing on memory address of f when tun is no longer on the stack does'nt the memory got destroyed?

No. There is no pointer to f in your code. This line

*(fun()) = f;

assigns the value of f to the int pointed to by the static pointer ptr returned by fun() .

It is similar to

int x = 0;
int* ptr = new int;
*ptr = x;            // assigns 0 to the int pointed to by ptr
std::cout << *ptr;   // prints 0
assert( ptr != &x);  // adress of x ist not ptr   !!!

This happens because you assign the value to the pointer created on the heap in fun , the variable f no logner exists

  #include <iostream>

static int* fun(){
  static int *ptr = new int(4); // 4 stored inside pointer
  return ptr;
}// ptr still exists because it's heap allocated

 static int * tun() noexcept{
   int f = 111; //f holds value 111
   *(fun()) = f; // ptr now stores the value 111
   return fun();
 } // f gets destroyed, ptr still holds 111

 static int *sun(){
  return tun();
}

int main() {
  std::cout << (*sun()) << std::endl;
}

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