2015-11-25 91 views
0

我想用SDL_CreateTextureFromSurface創建一個SDL_Texture。我已經多次成功地實現了這個功能,沒有問題。目前我正在以下回溯信息:SDL2 SIGSEGV從表面創建紋理

#0 0xb7ef1e80 in ??() from /usr/lib/libSDL2-2.0.so.0 
#1 0xb7edf19c in ??() from /usr/lib/libSDL2-2.0.so.0 
#2 0xb7f12e1d in ??() from /usr/lib/libSDL2-2.0.so.0 
#3 0xb7f13ee7 in ??() from /usr/lib/libSDL2-2.0.so.0 
#4 0xb7eb2c08 in ??() from /usr/lib/libSDL2-2.0.so.0 
#5 0xb7e9f474 in SDL_CreateTextureFromSurface() from /usr/lib/libSDL2-2.0.so.0 
#6 0x0805999e in Building::draw (this=0xbfffe9a8, [email protected]: 0x81bd1b8) 
    at /code/directory/LIBRARY.h:194 
#7 0x08063df7 in main (argc=1, args=0xbffffac4) at Program.cpp:1151 

我的代碼的其餘部分和這個特殊的實現之間唯一不同的是,我的SDL_Surface是一個指針數組定義如下:

//<Initialize window and renderer (not included here)> 
SDL_Surface** Surf; 
SDL_Surface* SomeOtherSurface; 
int SurfSize = 0; 

SomeOtherSurface = LoadBMP("Filename.bmp"); 
for (i = 0; i < 2; i++) 
{ 
    Surf = (SDL_Surface**) realloc(Surf,SurfSize+1)*sizeof(SDL_Surface*)); 

    SDL_LockSurface(SomeOtherSurface); 
    Surf[i] = SDL_CreateRGBSurfaceFrom(SomeOtherSurface->pixels,SomeOtherSurface->w,SomeOtherSurface->h,32,SomeOtherSurface->pitch,0xFF000000,0x00FF0000,0x0000FF00,0x000000FF); //Create a surface in Surf based on SomeOtherSurface 
    SDL_UnlockSurface(SomeOtherSurface); 
    SurfSize++; 
} 
SDL_FreeSurface(SomeOtherSurface); 
SDL_Texture* Tex1; 
Tex1 = SDL_CreateTextureFromSurface(Render,Surf[0]); //Create the texture; this throws the SIGSEGV 

我在程序的其他地方寫了類似的代碼,但並沒有失敗;任何人都可以找出這裏發生了什麼問題嗎?該錯誤似乎表明內存有問題,但如果我嘗試訪問Surf [0] - > w,它會按預期返回值。

編輯:一些額外的信息可以幫助解決這個問題:在我的代碼中,我定義紋理之前釋放'SomeOtherSurface'表面。如果我在釋放表面之前定義紋理,一切正常。這兩個表面可能共享像素數據地址嗎?

解決:我需要使用SDL_BlitSurface複製數據並修改它。如果我在使用SDL_CreateRGBSurfaceFrom之後繼續釋放表面,那麼當程序嘗試訪問該存儲器地址時,現有的像素數據也會被刪除,導致段錯誤。

+0

在你的實際代碼中,你是否將Surf初始化爲第一個realloc()之前的空指針?你在這裏呈現的realloc()調用不會編譯(最後的附加括號),但是你可能要仔細檢查你是否真的將realloc()返回的指針乘以一個指針的大小。 .. – notmyfriend

+0

是的,我錯過了一個開放的支架。在realloc之前,Surf沒有被初始化爲null。 – Arlington

+0

那麼..你應該在首次調用[realloc]之前將它初始化爲null(http://en.cppreference.com/w/c/memory/realloc)。否則,如果內存位置碰巧包含0以外的內容,那麼'realloc()'的行爲是不確定的,因爲傳遞的指針必須先被調用到'malloc()','calloc()'或'的realloc()'。 – notmyfriend

回答

1

該代碼的問題是SDL_CreateRGBSurfaceFrom使用現有的像素數據;因此,當您調用SDL_FreeSurface時,像素數據會丟失。現在,在調用SDL_CreateTextureFromSurface時,Surf [i]嘗試查找像素數據,並且內存不可訪問。

解決方案:使用SDL_BlitSurface複製像素數據以備後用。