Local variable goes out of scope and memory isnt released | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Local variable goes out of scope and memory isnt released

I learned that when a local variable goes out of scope it gets destroyed and memory gets released, if so, why can i go to that adress after memory gets released and access the value? https://code.sololearn.com/cP5MbDF7qpuW/?ref=app https://code.sololearn.com/cP5MbDF7qpuW/?ref=app

22nd Sep 2019, 6:35 PM
Denomycor
Denomycor - avatar
5 Answers
+ 1
You did not release any memory. You declared a pointer outside of main. Then within a local local scope you pointed the pointer to a value on the stack. Normaly if you declare a value in a local scope, you cannot access it outside of its scope. But you passed the variables address to the pointer. So you can keep accessing it.
22nd Sep 2019, 6:52 PM
Manual
Manual - avatar
+ 1
Oh I believed I had two comments here. Denomycor you need memory management for heap objects. Especially ones created using the "new" keyword. Read more here: http://www.cplusplus.com/doc/tutorial/dynamic/
22nd Sep 2019, 7:50 PM
Manual
Manual - avatar
+ 1
Denomycor Yes, they (local stack objects) do release memory. But releasing memory does not mean whatever is stored in a certain memory cell is destroyed. Rather, releasing memory means the operating system is notified that the certain memory cell(s) that were occupied so far may be used again to store new data there, as far as I understand. Unless that happens and the previously stored data is overwritten, it still exists, and therefore the pointer pointing to that cell still returns the value you stored there earlier. Please note that this is undefined behaviour, i.e. the language lets you get away with it, but it is not safe to assume that the data is still there.
22nd Sep 2019, 7:54 PM
Shadow
Shadow - avatar
0
Sry for the double link
22nd Sep 2019, 6:35 PM
Denomycor
Denomycor - avatar
0
soo local variables when destroyed dont release they memory?
22nd Sep 2019, 7:41 PM
Denomycor
Denomycor - avatar