• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Aluthreney

Deleting value stored inside a pointer

14 posts in this topic

So my situation is the following:

 

I have a pointer array that is initiated as NULL. The idea is that this array of pointers will hold instances of a class, which I create using the new operator:

 

myClass *ptr[10];
for(int x; x<=9; x++){ptr[x]=NULL;}

code...code...code...
ptr[5]=new myClass;
 

So far everything works fine, but now I need to know how to delete the instance inside the pointer without deleting the pointer / pointer array, itself.

 

Your help is appreciated biggrin.png

0

Share this post


Link to post
Share on other sites
You need to call delete for everything you call new for. You call new for ptr[x], for each x in the array, so you need to call delete for ptr[x] as well.
for(int x=0; x<10; ++x) {
    delete ptr[x];
}
Edited by Brother Bob
1

Share this post


Link to post
Share on other sites
[tt]delete ptr[5];[/tt]

You can't (shouldn't) delete [tt]ptr[/tt] because it wasn't [tt]new[/tt]ed:
myClass** arr = new myClass*[10];
for ( auto& obj : arr )
    obj = new myClass();

// ...

for ( auto& obj : arr )
    delete obj;
delete[] arr;
1

Share this post


Link to post
Share on other sites

You need to call delete for everything you call new for. You call new for ptr[x], for each x in the array, so you need to call delete for ptr[x] as well.

for(int x=0; x<10; ++x) {
    delete ptr[x];
}

I tried doing this, but it didn't do anything. The class instance contains a 3d object that is rendered when I run the program. Supposedly, when I delete the contents inside the  pointer (using delete ptr[x]) the image wont render when I run the program, but it does...

 

[tt]delete ptr[5];[/tt]

You can't (shouldn't) delete [tt]ptr[/tt] because it wasn't [tt]new[/tt]ed:

myClass** arr = new myClass*[10];
for ( auto& obj : arr )
    obj = new myClass();

// ...

for ( auto& obj : arr )
    delete obj;
delete[] arr;

I don't want to delete the pointer only what it's pointing to.

0

Share this post


Link to post
Share on other sites

If you delete the objects you have allocated, but then keep using the objects afterwards, your program is ill-formed. That does not mean that your program must crash or must produce an incorrect result. It may do that, but it doesn't have to. Nevertheless, your program is ill-formed.

1

Share this post


Link to post
Share on other sites
Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.
delete ptr[x];
ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
0

Share this post


Link to post
Share on other sites

Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.

delete ptr[x];
ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.

If you need to litter your code with null-checks, then you have ownership issues that needs to be solved instead. You should not ask yourself if you need to check for null before accessing a pointer, you should ask yourself why the pointer can be deleted in the first place if you still need it.

0

Share this post


Link to post
Share on other sites




Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.

delete ptr[x];ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
If you need to litter your code with null-checks, then you have ownership issues that needs to be solved instead. You should not ask yourself if you need to check for null before accessing a pointer, you should ask yourself why the pointer can be deleted in the first place if you still need it.

If you delete the objects you have allocated, but then keep using the objects afterwards, your program is ill-formed. That does not mean that your program must crash or must produce an incorrect result. It may do that, but it doesn't have to. Nevertheless, your program is ill-formed.

I never said I was going to keep using the objects after I delete them. I said I was going to use the pointers and I don't want to delete the pointers, I want to delete what the pointers are pointing to.

Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.

delete ptr[x];ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
I was already planning for this though.
----------
Let me try and explain my idea.

I have two classes: class Monster and class Spawner.
The Monster class will have basic functions for movement, animations and keeping track of it's health, but it's the Spawner class that will control the creation and destruction of the Monster class instances.

So in the Spawner class I decided to create a pointer array of Monster class and also created two functions: createMonster() and killMonster().


//! definition of the createMonster() function...//! keep in mind that the pointer array has already been given the NULL value.
void createMonster()
{    
    while(int x; x<=9; x++)    
    {        
        if(ptr[x]==NULL)        
        {            
            ptr[x]= new Monster;        
        }    
    }
}


//! definition of the createMonster() function...
void killMonster(int x) //! the parameter is the particular pointer in the array that I want to clear.
{    
    code...code...code...    
    //! The line of code that will destroy the instance of the Monster class so that I can make the pointer NULL, in order to be re-    
    //! utilized at a later date to hold a new instance of the Monster class, goes here.    
    ptr[x]=NULL;
}
The code might look a bit empty, but I stripped it down to the bare bones in order to clarify the idea I'm trying to convey. Edited by Aluthreney
0

Share this post


Link to post
Share on other sites

Others have a handle on the specifics, but I saw some terminology mix-ups here that I wanted to ensure weren't holding you up as well. (I see them all the time with people learning C/C++.)

 

I have a pointer array that is initiated as NULL. The idea is that this array of pointers will hold instances of a class, which I create using the new operator...

So far everything works fine, but now I need to know how to delete the instance inside the pointer without deleting the pointer / pointer array, itself.

Your array of pointers won't "hold instances of a class". It will hold pointers: a list of addresses were instances of your class can be held. When you invoke the new operator, it instantiates whatever class you pointed it at and returns the address where that instance lives, which you land in your array of pointers there.
 

As others have explained, when you invoke the delete operator on an address, the delete operator will kill the instance of your class that lives there. This is where things can get tricky at times and is why you need to know the full picture here.

 

If you delete an instance but reference it later (because you still have the address in that pointer array) you'll get a seg fault; it's why it's a good idea to set a pointer to null after you delete it. This stuff can also be the source of memory leaks (if you lose that pointer before you delete the memory you allocated with new, that memory is never released and just hangs out, dead and wasting space.

 

I hope this is helpful. <3 Good luck.

0

Share this post


Link to post
Share on other sites





Deleting something doesn't automatically set the pointer to null. You'll need to nullify it yourself.

delete ptr[x];ptr[x] = NULL;
But if you take this approach, then you need to check for NULL every time you access the array.
If you need to litter your code with null-checks, then you have ownership issues that needs to be solved instead. You should not ask yourself if you need to check for null before accessing a pointer, you should ask yourself why the pointer can be deleted in the first place if you still need it.

If you delete the objects you have allocated, but then keep using the objects afterwards, your program is ill-formed. That does not mean that your program must crash or must produce an incorrect result. It may do that, but it doesn't have to. Nevertheless, your program is ill-formed.

I never said I was going to keep using the objects after I delete them. I said I was going to use the pointers and I don't want to delete the pointers, I want to delete what the pointers are pointing to.
The term "delete a pointer" means just that; you delete the object the pointer points to. That is, delete ptr does not delete ptr itself, it delete what ptr points to.
1

Share this post


Link to post
Share on other sites

Ok I got it working thank you everyone for your advice, it really helped. Just one last question though: Even though the instance of the Monster disappears on screen (3d object is not rendered), is there a way to make sure the memory that was holding the instance is properly "cleaned"?

0

Share this post


Link to post
Share on other sites
If you called delete on it, the memory of the object the pointer points to have been deleted. Furthermore, the destructor for the object will also be called before the actual memory is released so you can do additional cleanup there so no indirect resources are leaked. Edited by Brother Bob
0

Share this post


Link to post
Share on other sites

Ok I got it working thank you everyone for your advice, it really helped. Just one last question though: Even though the instance of the Monster disappears on screen (3d object is not rendered), is there a way to make sure the memory that was holding the instance is properly "cleaned"?

 

No. It depends on the runtime and the operating system. For all you know it could be cached somewhere else in memory, or even in the swapfile on disk. But you should not have to even care what happened to the underlying memory, as long as you properly issued the delete statement indicating you no longer require use of this instance (unless you need it to be securely deleted, for security reasons or whatever).

 

In other words, if you've deleted the appropriate pointers, your worries end right there. From your perspective, everything happening at a lower level is assumed to work.

Edited by Bacterius
0

Share this post


Link to post
Share on other sites
Depending on your platform and compiler you may be able to use a leak detector to determine if all your dynamically allocated memory has been properly freed. This thread contains some options. For non-memory resources there may be other tools available to check if they've been freed. (Ex: the DirectX debug runtimes will give you warnings if you haven't released everything and Windows Application Verifier can be used to detect leaked OS handles.)
0

Share this post


Link to post
Share on other sites

If you call delete(ptr[5]), it is telling the OS that you no longer need the memory pointed to by ptr[5]. However! delete() will not re-initialize that memory for you. You can think of it like a sand castle -- when you call new(), you draw a square on the beach to mark off the area you will use for your castle. Inside the square, the sand starts out in some random state, all lumpy with footprints from everyone else walking all over the beach. Then you use a constructor or initializer to shape the memory, forming your sand castle. Since you have your lines drawn in the sand, everyone else avoids your sand castle, and only you are allowed to touch it.

 

When you call delete(), you erase the lines in the sand. Your sand castle is still there, and you can still point to it, but it is no longer marked as off limits for others. Eventually people will start walking through it and claiming that sand for themselves, and moving pieces of your castle around to make their own. You can still point to the spot your castle used to be at, but your castle may or may not still be there -- it could also contain bits and pieces of random castles created by other people.

 

In this metaphor, your question would be "How do I make my sand castle perfectly flat when I'm done with it?" You could do that using something like memset(ptr[5], 0xDD, sizeof(MyClass)), to overwrite all the memory used by MyClass to 0xDD, so that you can more easily detect if something is trying to access freed memory. This is a fairly advanced memory debugging technique though, which is only really useful if you are trying to track down a memory corruption error. Otherwise, re-initializing memory when deleting a pointer is a waste of developer and execution time.

 

You should also be aware that nobody else is re-initializing their memory when they free it, so whenever you block off some memory with malloc() or new(), it will start out in a random state -- it will not be nicely zeroed like you might expect. If you call int* test = new int, then *test will usually not equal zero. It will probably be some strange number, like -842150451, because that's what it was set to when some other function or program freed it.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0