Stack memory allocation

They say that a local variable will be allocated and automatically freed when the function ends in C / C ++.

According to my understanding, when it was released, the value held by the local variable will also be destroyed !!! Please correct me if I am wrong

Consider the following code:

void doSomething(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 ???
}

Can anyone clarify for me?

+3
source share
4 answers

You're right. your cout may or may not type 10. It will cause undefined behavior.


To take a little more note, try running the following code under your compiler without enabling optimization.

#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!
}
+8
source

a . . undefined. 10, ( , , ).

+5

. num , - , , 10.

+1

. , , , , .

. out :

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;
}

, - , :

int doSomething()
{
  return 10;
}

int main()
{
  std::cout << doSomething() << std::endl;
}
+1
source

Source: https://habr.com/ru/post/1779628/


All Articles