Search code examples
c++imagesdlcopy-constructorcopy-assignment

Custom copy assignment operator crashes the program (C++)


I'm creating a custom class for automaticly cleaning up memory. The class contains a pointer to an SDL_Surface object and calls it's refcount when needed. The problem is when I implement the custom copy assigment operator the system crashes with the following code:

"Unhandled exception at 0x771a15de in xyz.exe: 0xC0000005: Access violation reading location 0xcccccd04."

and the object attribute "address" suddenly gets the value "0x0000ffff ", whilst using the default copy assignment operator it runs perfectly fine.


Solution

  • You're using the refcount incorrectly. SDL_FreeSurface will decrement the refcount, and when called on a null pointer, is a no-op. So, your assignment operator should look like this:

    const Image& Image::operator=(const Image& other){
        if (img != other.img){
            SDL_FreeSurface(img);
            img = other.img;
            if (img != NULL)
                img->refcount++;
        }
        return *this;
    }
    

    And your destructor should look like this:

    Image::~Image(){
        SDL_FreeSurface(img);
    }
    

    Also, in your default constructor, you should initialize img to a null pointer.

    Image::Image() :img(NULL) {}
    

    See the second to last example on this page: http://sdl.beuc.net/sdl.wiki/SDL_Surface