Welcome! Log In Create A New Profile

Advanced

correct way to delete?

Posted by SteelSLasher 
correct way to delete?
January 03, 2010 08:14PM
in my game engine the images to be drawn are stored in a vector similarly to libwiigui (most of my graphics coding is inspired by libwiigui) and i want to clear the vector of images, since the vector is a set of pointers i thought it would be correct to use delete but this seems to cause a hang in the code probably because i have kept to my php habits of being reckless

i have put all the required info below including the structs for the variables in question:
typedef struct element{
    SDL_Surface *image; //actual image for element
    int x; //x pos
    int y; //y pos
    int xvel; //velocity in x direction in pixels
    int yvel; //velocity in y direction in pixels
    int interval; //sets movements speed i.e setting to 50 would mean one movement per 50ms, allows slow movements
    SDL_Rect area; //part of image to display, default to entire image, allows tilesets for animating
};

vector<element*> elements;
vector<element*> overlays;

void free_surfaces()
{
    for (unsigned int i = 0; i < elements.size(); i++)
    {
        delete elements;
    }
    elements.clear();
    for (unsigned int i = 0; i < overlays.size(); i++)
    {
        delete overlays;
    }
    overlays.clear();
}

i am almost ready to make a demo app, i just need to finish this
Re: correct way to delete?
January 03, 2010 08:18PM
If there's a destructor, you should call the destructor before deleteing them.
Re: correct way to delete?
January 04, 2010 01:15PM
Quote
Arikado
If there's a destructor, you should call the destructor before deleteing them.
Destructors are called by delete.

How did you fill the vector? If you use malloc to create something and then delete to destroy it then things will go wrong.
Re: correct way to delete?
January 04, 2010 09:04PM
the vector is filled with push_back(), and the vector is just a list of pointers
Re: correct way to delete?
January 05, 2010 05:40AM
If they're just pointers I assume you allocated, so deallocate using free(x), where x is a pointer to the region you'd recently allocated.

If your using C++, you can deallocate a region using the delete keyword, and allocate using the new keyword.
In C you allocate via malloc method, and deallocate via free.

I'm not sure how element::image is allocated, but it probably needs to be deallocated as well. It's possible the 'SDL' header defines some method which deallocates an SDL_Surface.
Sorry, only registered users may post in this forum.

Click here to login