preventing errors

hi everyone.

i come across with a problem which i solved but the thing i wonder is

1
2
SDL_FreeSurface(surf);
mTex = CreateTextureFromSurface(renderer, surf);


it was like this you see. before using it i mistakenly freed the surface. i fixed it now but.

CreateTextureFromSurface func should be able to understand whether it is NULL or not but the surface does not even exist(i guess) so it causes error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
SDL_Texture * texture::CreateTextureFromSurface(Renderer * renderer, Surface * surface)
{
    core cr;

    SDL_Texture * tmp;

    if(!renderer)
        cr.Logger("at function \"texture::CreateTextureFromSurface\" renderer can not be NULL");
    else
    {
        if(!surface)
            cr.Logger("at function \"texture::CreateTextureFromSurface\" surface can not be NULL");
        else
        {
            tmp = SDL_CreateTextureFromSurface(renderer, surface);
        }
    }

    if(!tmp)
        cr.Logger("at function \"texture::CreateTextureFromSurface\" failed to create texture");

    return tmp;
}


do you know how can i understand if it is freed or not??
Last edited on
do you know how can i understand if it is freed or not??


You can't.

If you have a non-null pointer there is no way to know whether or not the data it points to is valid.


The common approach to prevent this problem is either:

1) Always set your pointers to null after freeing them.
or
2) Put your pointers in some kind of container that does the creation/freeing and allows you to poll their state.
Perhaps follow solution 1 over there.
Setting them to null after freeing them is the way to go.
> Setting them to null after freeing them is the way to go.

RAII is the way to go. Use smart pointers (painless and exception-safe).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::shared_ptr<SDL_Surface> surface( SDL_LoadBMP("whatever.bmp"), &SDL_FreeSurface ) ;

// ...

if( some condition ) surface = nullptr ; // free the surface

// ...

if(surface) // if surface was not freed
{
    // use surface
    SDL_Surface* s = surface.get() ; 

    // ...
}
ok i choose the first option then.

thx to all of you
Topic archived. No new replies allowed.