I have a question regarding the memory management in C++. As far as I know, there is no need to deallocate memory in Java, since unused objects will be removed by the JVM garbage collector at some time. My point is, if I forgot to free memory in C++, the used memory addresses will be occupied until I restart the machine and the data in the memory get lost? For example, on the code below I have a simple linked list and you can observe that I do not free memory(which is commented in the destructor):
#include <iostream>
using namespace std;
typedef struct Node{
Node* next;
int id;
} *ListPtr;
class LinkedList{
public:`ListPtr header;
LinkedList(){
header = NULL;
}
~LinkedList(){
/*
ListPtr a = header,b;
while(a != NULL)
{
b = a;
a = a -> next;
delete b;
}
delete a,b;
cout << "Memory freed!"<< endl;
*/
}
public: void Insert(){
ListPtr new_element = new Node;
new_element -> next = NULL;
if(header == NULL){
header = new_element;
header -> id = 0;
}
else{
new_element -> next = header;
new_element -> id = header -> id + 1;
header = new_element;
}
}
public: void Print(){
ListPtr curr = header;
while(curr != NULL){
cout << "[" << &curr -> id << "]" << "-->";
curr = curr -> next;
}
cout << "[NULL]"<<endl;
}};
int main(){
LinkedList list;
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Print();
return 0;
}
Does it mean that those memory addresses will be occupied until I turn the machine off? What happens with variables such as integers after the execution of a program is done? Can I free them?
The Output for the program is: [0x8622ac]-->[0x86229c]-->[0x86228c]-->[0x86227c]-->[0x8615bc]-->[NULL]