Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to memory of variable after loops? (C++)

Tags:

c++

memory

i'm trying to understand how C++ works. When u declare a new variable (int x) within a loop, for example within a for-loop. Memory is allocated to the variable x within the loop, but what happens to that memory after exiting the for-loop? My understanding from a friend is that Java will automatically de-allocate the memory, but what about C++?

Thanks.

like image 817
Cherple Avatar asked Feb 13 '23 04:02

Cherple


1 Answers

It will be deallocated if declared on stack (i.e. via int x = ...) and when the variable leaves its scope. It won't be deallocated if declared on heap (i.e. via int *x = new int(...)). In that case you have to explicitely use delete operator.

like image 135
freakish Avatar answered Mar 04 '23 08:03

freakish