2014-09-26 92 views
0

我在學習SDL 2.0,我一直在關注lazyfoo教程。問題在於這些教程將所有內容都保存在一個文件中。所以我試圖在開始一個新的遊戲項目時分割一些東西。我的問題是,當我從其餘的分離我的紋理類時,它有時會崩潰程序,並不總是,但經常。SDL從文件加載圖像

我有一個全局窗口和全局渲染器,我在我的課堂上使用。我在程序中的不同位置獲得段錯誤,但始終處於以下功能之一中。

bool myTexture::loadFromFile(string path) { 
    printf("In loadFromFile\n"); 

    //Free preexisting texture 
    free(); 
    //The final texture 
    SDL_Texture *l_newTexture = NULL; 

    //Load image at specified path 
    SDL_Surface *l_loadedSurface = IMG_Load(path.c_str()); 
    if(l_loadedSurface == NULL) { 
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(),  IMG_GetError()); 
    } else { 
    //Color key image for transparancy 
    //SDL_SetColorKey(l_loadedSurface, SDL_TRUE, SDL_MapRGB(l_loadedSurface->format, 0, 0xFF, 0xFF)); 
    //Create texture from surface pixels 
    l_newTexture = SDL_CreateTextureFromSurface(g_renderer, l_loadedSurface); 

    if(l_newTexture == NULL) { 
     printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); 
    } else { 
     //Get image dimensions 
     m_width = l_loadedSurface->w; 
     m_height = l_loadedSurface->h; 
    } 
    //Get rid of old loaded surface 
    SDL_FreeSurface(l_loadedSurface); 
    } 
    m_texture = l_newTexture; 
    //return success 
    printf("end from file \n"); 

    return m_texture != NULL; 
} 

void myTexture::free() { 
    printf("In myTexture::free\n"); 
    //Free texture if it exist 
    if(m_texture != NULL) { 
    cout << (m_texture != NULL) << endl; 
    SDL_DestroyTexture(m_texture); 
    printf("Destroyed m_texture\n"); 
    m_texture = NULL; 
    m_width = 0; 
    m_height = 0; 
    } 
    printf("end free\n"); 
} 

閱讀SDL和其他東西后,我明白,可能有一些線程試圖解除分配的東西,它是不允許解除分配。不過,我還沒有任何線程。

+0

'm_texture'初始化爲'myTexture'構造函數中的空指針嗎? – rems4e 2014-09-26 09:09:34

+0

是的,這裏是構造函數 myTexture :: myTexture(){ //初始化 m_texture = NULL; m_width = 0; m_height = 0; } – Redhat 2014-09-26 09:34:11

+0

在開始修改它之前,它是否像LazyFoo的教程中顯示的那樣工作? – Zammalad 2014-09-26 10:48:03

回答

0

我設法解決這個由我自己。事實證明,我從來沒有創建一個真正愚蠢的新的myTexture對象。但我仍然不明白它是如何設法使它有時......對我而言,它根本沒有任何意義。我從來沒有創建它,但我仍然可以有時調用它的渲染函數...