views:

293

answers:

2

As I stated in this question, I am using SDL for a small game I'm developing. Now I am having problems with SDL_DisplayFormatAlpha. I am trying to create a surface with an alpha channel from a PNG image. It was working before, but now that I've done some slight refactoring something got broken. I've narrowed it down to this constructor:


Surface::Surface( tfilename file ) {
    // initialize the surface data member to the image indicated by filename
    SDL_Surface *tempSurface;
    tempSurface = IMG_Load( file.c_str() );
    if ( !tempSurface ) {
     surface = NULL;
     exit(1);
    }
    else {
     surface = SDL_DisplayFormatAlpha( tempSurface );
     //surface = tempSurface;
    }
    SDL_FreeSurface( tempSurface );
}
This compiles just fine, but when I run it I get a Segmentation fault. The error reported by gdb:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb79c16c0 (LWP 8089)]
0xb7e8b9a3 in SDL_DisplayFormatAlpha () from /usr/lib/libSDL-1.2.so.0

The stack trace is as follows:

#0  0xb7e8b9a3 in SDL_DisplayFormatAlpha () from /usr/lib/libSDL-1.2.so.0
#1  0x0804987e in Surface (this=0x804d060, file=@0xbfb20760) at Surface.cpp:16
#2  0x0804a159 in Image (this=0x804d038, x=0, y=0, file=@0xbfb207a0)
    at Image.cpp:16
#3  0x0804a3de in Object (this=0x804d028, imageFile=@0xbfb207dc)
    at Object.cpp:4
#4  0x080491cb in Application (this=0xbfb20810) at Application.cpp:8
#5  0x08048e0d in main () at main.cpp:5

If I comment out surface = SDL_DisplayFormatAlpha( tempSurface ); and SDL_FreeSurface( tempSurface ); and uncomment surface = tempSurface; like so:



Surface::Surface( tfilename file ) {
    // initialize the surface data member to the image indicated by filename
    SDL_Surface *tempSurface;
    tempSurface = IMG_Load( file.c_str() );
    if ( !tempSurface ) {
     surface = NULL;
     exit(1);
    }
    else {
     //surface = SDL_DisplayFormatAlpha( tempSurface );
     surface = tempSurface;
    }
    //SDL_FreeSurface( tempSurface );
}

Then it seems to work just fine. Can anyone tell me what's going on? Actually, the transparency seems to work, too when I comment out SDL_DisplayFormatAlpha. Is that function only meant to be used with images that do not already have an alpha channel?

+1  A: 

IMG_Load should handle transparent PNG's automatically, as the end of your post notes. What is the actual exception/error being thrown? Your stack trace doesn't show that.

grepsedawk
I've added the actual error reported by gdb.
Steven Oxley
A: 

If you read the link here (related function):

SDL_DisplayFormat

"You have to call SDL_Init before using the SDL_DisplayFormat function. If you don't, your program will crash with an access violation."

Could that be your problem?

Sydius