Skip to main content
GameDev.net gamedev.net
🔒 Locked

Setting a pointer to NULL

Started by _ArmuT_ Jan 18, 2008 at 11:11 PM 1 replies 2.1k views
Original Post
_ArmuT_
_ArmuT_
Hi Guys, Here is the thing.. Assume that we have 3 classes. ClassA, ClassB and ClassC. ClassB holds an array of pointers to ClassA created by new.

// This is in ClassB
ClassA** myPtr;
myPtr = new ClassA*[100];




and lets assume that I am using an accessor function to this pointer array, smtg like:

//This is in ClassB (1)
ClassA* myPointer(void){return myPtr[index];}




And in ClassC, I want to get a hold to this pointer Array. So what I tried is to pass the pointer to ClassC from ClassB's accessor function(1). ClassC uses new to hold the incoming pointers in an array. Ok so far everything seems working. Here is my problem. I know that I cannot use delete, delete[] for my pointer array in ClassC. Because doing so result in deleting the ClassA objects in the heap, which is originally created by ClassB and suppose to live on after the destruction of ClassC. So what I did in ClassC is, instead of deleting the pointer array,I set all pointers in the array to NULL in the destructor. But does this approach in ClassC (after destruction of ClassC)free the memory that holds the pointers to ClassA created by ClassB ? Thanks in advance!
Exab
Exab
If your array of pointers in ClassC looks someting like you did in ClassB:

// This is in ClassCClassA** myNewPtr;myNewPtr = new ClassA*[100];


You can simply do:

delete[] myNewPtr;


You won't delete the ClassA objects, you have ClassA** myNewPtr, you have a double pointer so it will only delete what is pointed by myNewPtr which is a ClassA*, which is nothing more than a pointer.

When you call delete on something, remove a * and if there are no more *, then memory is freed. In your case if you _wanted_ to delete ClassA objects from ClassC, you'd have to loop through your array and do: delete myNewPtr; ( [] automaticaly derefences myNewPtr, removing a *, then delete removes another * and what's left is a ClassA, in the case of just doing delete[] myNewPtr;, only a single * is dereferenced).

From what I understand, you'd have a memory leak if you only set those pointers to NULL, not much, 100 * sizeof( ClassA* ), which would be 400 bytes usually.


I think I talk too much sometimes, I hope I didn't mix things up for you. :)
Mushu
Mushu
Also, consider taking a look at Boost.Shared_Array which is a reference-counted smart pointer object for arrays, if you're not changing the contents or structure of your array of ClassA pointers when you give them to ClassC.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.