开发者

Stack memory allocation

开发者 https://www.devze.com 2023-01-29 17:51 出处:网络
It is being said that local variable will be allocated and deallocated automatically when function ends in C/C++.

It is being said that local variable will be allocated and deallocated automatically when function ends in C/C++.

According to my understanding, when having been deallocated, the value held by local variable also be destroyed!!! Please correct me if i'm wrong

Consider following code:

void doSomet开发者_高级运维hing(int** num)
{
  int a = 10;
  *num = &a;
} // end of function and a will be destroyed

void main()
{
  int* number;
  doSomething(&number);
  cout << *number << endl;  // print 10 ???
}

Could anybody clarify for me?


You are correct. your cout may or may NOT print 10. It will invoke undefined behavior.


To make a bit more of a note, try running the following code under your compiler with no optimizations enabled.

#include <iostream>
using namespace std;

void doSomething(int** num)
{
    int a = 10;
    *num = &a;
}

void doSomethingElse() {
    int x = 20;
}

int main()
{
    int* number;
    doSomething(&number);
    doSomethingElse();
    cout << *number << endl; // This will probably print 20!
}


In this case, the integer a is on the stack. You are returning the address of that variable to the main program. The value at that address location after the call is undefined. It is possible in some situations that it could print 10 if that portion of the stack was not overwritten (but you certainly would not want to rely on it).


The content of the memory isn't actually destroyed. For this case, num will point to a location which isn't being allocated for any variable, but it will hold it's content, which was set to 10.


The memory being pointed to has been released back to the system. That means that it will hold whatever value it had until the system assigns that block of memory to another variable and it gets overridden with a value.

Local variables are released when they go out of scope. If you are trying to return a value using an out parameter to a function:

void doSomething(int** num)
{
  int* a = new int;
  *a = 10;
  *num = a;
}

int main()
{
  int* number = 0;
  doSomething(&number);
  std::cout << *number << std::endl;  // print 10 ???
  if (number) delete number;
}

Though, for something this simple, you are better off just doing this:

int doSomething()
{
  return 10;
}

int main()
{
  std::cout << doSomething() << std::endl;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号