SandBag_1996
SandBag_1996

Reputation: 1601

Garbage memory?

I was just going through an article which explains about Wild pointers. For garbage memory, it states that when a pointer pointing to a memory object is lost, i.e. it indicates that the memory item continues to exits, but the pointer to it is lost; it happens when memory is not released explicitly. I was trying to understand this with an example. Here is what I wrote

#include <iostream>

using namespace std;
int q =12;
int point()
{
   int *p;
   p = &q;
   //delete p;
}
int main()
{
   point();
   return 0;
}

So, in the above example, memory item (q) continues to exist, but the pointer to it is lost. I may have misunderstood it all wrong, but if I understood it correctly, then does this example addresses 'garbage memory' definition given above? If yes, then I should use delete p, right?

Upvotes: 2

Views: 762

Answers (1)

Karthik T
Karthik T

Reputation: 31952

C++ Does not have garbage collection the way you understand it.. But what you are showing is not a "memory leak" which is what I think you mean.

In this case you are pointing to a memory location that is NOT dynamically allocated, and is accessible from outside the function for the duration of the program.


int point()
{
   int *p = new int();
   //delete p;
}

This is now a memory leak, since the memory is still allocated, but noone can access it any more. If this were Java or any other language which supports GC, this memory would now be queued to be Garbage collected.


The recommended style in C++ is to make all allocated memory auto deallocate themselves, as far as possible, with a concept called Resource Acquisition Is Initialization (RAII), using smart pointers as below.

int point()
{
   std::unique_ptr<int> p(new int());
   //delete p;  // not needed.
}

When the variable p is destroyed, at the end of its scope, it will automatically call delete on the allocated memory so you dont have to. By making stuff clean up after themselves, we enable the below.

C++ is my favorite garbage collected language because it generates so little garbage

Bjarne Stroustrup's FAQ: Did you really say that?. Retrieved on 2007-11-15. http://en.wikiquote.org/wiki/Bjarne_Stroustrup

Upvotes: 10

Related Questions