【发布时间】:2014-11-18 00:12:37
【问题描述】:
我正在尝试学习 SDL 2.0,并且一直在关注lazyfoo 教程。问题是这些教程将所有内容都保存在一个文件中。所以我在开始一个新的游戏项目时试图把一些东西分开。我的问题是,当我将纹理类与其他纹理类分开时,它有时会导致程序崩溃,但并非总是如此。
我在课堂上使用了一个全局窗口和一个全局渲染器。我在程序的不同位置遇到段错误,但总是在以下函数之一中。
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 和其他内容后,我了解到可能有一些线程试图释放它不允许释放的东西。但是我还没有线程任何东西。
【问题讨论】:
-
m_texture是否在myTexture构造函数中初始化为空指针? -
是的,这里是构造函数 myTexture::myTexture() { //初始化 m_texture = NULL; m_width = 0; m_height = 0; }
-
在开始修改之前,您是否按照 LazyFoo 的教程中显示的那样工作?
-
代码看起来不错。在调试器中运行它以查看崩溃的确切位置以及当时变量的值。
-
是的zammalad。问题是它在这些函数的不同点崩溃,所以我在找出导致它崩溃的原因时遇到了问题。有时它运行得很好。即使它总是在其中一个函数中崩溃,程序的其他部分是否也会导致它崩溃?