NANDAKUMAR THANGAVELU
NANDAKUMAR THANGAVELU

Reputation: 661

Deallocate memory on unused objects forcelly

Lets consider the following scenario in the Single Linked List:-

I have been given the target node, which is going to be deleted.

Lets assume the following data and I am going to receive the object which holds "3", which is the one I am going to delete;

1 -> 2 -> 3 -> 4 -> 5 -> 6

And Class Structure is:-

Class DataHolder
{
int data;
DataHolder nxtPrt;
}

Void Delete (DataHolder currentData)
{

currentData.data = currentData.nxtPrt.data; //Now 3 will be overwritten by 4
(x) currentData.nxtPrt = (y) currentData.nxtPrt.nxtPrt;  

//Now the object which belongs to 4 (previously it was 3), 
//is pointing to 5;

}

So, now the actual copy of the object 4 is now become useless;

So, now i just want to remove the space allotted to original copy of 4;

But, now I cannot track it also since, I have altered the object to point 5.

So right now, at this point I have lost the actual object 4.

May I Kindly know, is there any way to forcefully ask the object to release its occupied memory like doing in "C" using dealloc, or I have to depend on the GC to collect the unused space upon its wish.

Thanks in advance.

Upvotes: 0

Views: 402

Answers (1)

Luaan
Luaan

Reputation: 63772

You're always relying on the GC, there's no way around it. And yes, it will clean up your other objects, as long as there's no reference to them. You can allocate unmanaged memory and deal with it as you see fit but, in that case, why are you using C#? Just use C(++).

But the simplest answer is don't write your own linked list. Just use LinkedList<YourStruct>. Learn your environment - the language(s), the libraries and the runtime. If you're just going to write C code in C#, you're going to hurt, nobody's going to understand your code and you gain hardly any benefit from working in C#. Again, if you don't want to use C#/.NET... don't. There's nothing inherently wrong with C or C++, or with unmanaged languages. Use the best tool for the job.

Don't think in C terms at all. It simply doesn't work in a GC'd/managed environment. Where does memory come from when you allocate it in C? Usually the stack or the heap, with a few bits in registers. In .NET, this is kind of abstracted away, but in practice, you still only have those three locations. However, they work differently. You can't allocate classes or arrays on a stack (there's limited support using unsafe code, but that's it). There's multiple heaps, and apart from the large object heap, they always allocate from the top, similar to a stack. So deallocating a single object has no value whatsoever - if you don't compact the heap to eliminate the free spots, you don't get less memory usage, and you don't get any extra space for new objects.

Upvotes: 2

Related Questions