Doubt in stack order

sir when int * fun() could not return address of ‘a’. then how are wee getting int *b= fun() be same as ‘a’.

Hello @tejuschaturvedi0 i didnt get what exactly you are asking?

Sir in the video sir has said that the memory of fun will get erased after its use and thus could not return anything . So how int * b= fun() is getting same output address as address of a

@tejuschaturvedi0 the call will be over in int * b= fun()
this line only.
after this line only the array will be destrtoyed and the memory will be gone.

@tarunluthra
@rhlbhrdwj3

pls check . . . . . .

@tejuschaturvedi0
The reason b is getting the same address as that of a is because a was declared as an array inside the function fun() . When the value of a is returned at the end of the function, the memory address pointing to the beginning of the array is returned and that gets stored inside b. Now as soon as the function call is over, all data variables are destroyed which means the containers storing the values are destroyed. The values themselves are not destroyed. If another variable was able to store those values, then those values are going to persist.
In the above case, the memory address stored by a was destroyed. However, before it was destroyed, we had already stored its value in b.
Further you would notice that most compilers would give you a warning like this

warning: address of local variable 'a' returned [-Wreturn-local-addr]
     int a[] = {0, 1, 2, 3, 4, 5};

A better way to write this code to avoid the warning is

int *a = new int[6] {0, 1, 2, 3, 4, 5};

Declare the array dynamically so it no longer exists are a data variable of the function but rather in the heap memory itself. This will ensure that you can freely access the array using the b pointer after the function call is over.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.