Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens to unused memory in C++

I was going through some practice coding problems , and i came across one -

Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.

EXAMPLE:
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e

The solution to this is to simply copy the data from the next node into this node and then delete the next node.

The above solution is keeping java in mind, as the programming language. I am wondering what would happen to the content of deleted node? Will its fate be different in java and c++? And also, i think the perfect answer to this question should also deallocate the memory of the deleted node. How do we do that in c++?

like image 907
Nitin Garg Avatar asked Jan 20 '23 11:01

Nitin Garg


2 Answers

should also deallocate the memory of the deleted node.

Yes.

How do we do that in c++?

With the delete operator.

You probably getting ahead of yourself if you're working on link lists and don't know about the delete operator. You don't want to skip steps when learning C or C++; it will bite your head off later.

like image 175
Mud Avatar answered Jan 31 '23 07:01

Mud


In Java, the memory could eventually be freed by the garbage collector. There is no guarantee of when (and therefore, if) that happens. (In practice, it will usually happen very quickly).

In C++ with smart pointers, the deallocation of memory is guaranteed as soon as the object cannot be addressed anymore. In effect, it works pretty much like garbage collection in Java as long as you don't have any circular reference graphs.

If you are not using smart pointers, you'll have to manually call delete c (or free(c)). If you don't do this, your program will have allocated memory it can never use again.

like image 20
phihag Avatar answered Jan 31 '23 09:01

phihag