我正在使用C ++ SDL2库创建游戏。我的游戏在屏幕顶部有一个状态栏,应该在每次移动后更新。但是,更新只能工作一次。再次更新会导致程序崩溃。
我做了一些测试,发现使用SDL_CreateTextureFromSurface()
这是我使用的功能。
//screen* is a pointer to an object that contains all screen information
// such as dimensions, the renderer, the surface and the window object
void status_bar::update(int B, const char* E, screen* display){
if(B == 0){ //color is declared in status_bar object
color.r = 0;
color.g = 255;
color.b = 0;
}else{
color.r = 255;
color.g = 255;
color.b = 255;
}
SDL_Surface* temp_surf = TTF_RenderText_Solid(font, std::to_string(long double(B)).c_str(), color);
balanceRECT = temp_surf->clip_rect;
if(!balanceTEXT){
SDL_DestroyTexture(balanceTEXT);
}
balanceTEXT = SDL_CreateTextureFromSurface(display->Renderer, temp_surf); //Here the program crashes
balanceRECT.x = B_Mid_Coord.x - (balanceRECT.w / 2);
balanceRECT.y = B_Mid_Coord.y - (balanceRECT.h / 2);
SDL_FreeSurface(temp_surf);
temp_surf = TTF_RenderText_Solid(font, E, white);
energyRECT = temp_surf->clip_rect;
if(!energyTEXT){
SDL_DestroyTexture(energyTEXT);
}
energyTEXT = SDL_CreateTextureFromSurface(display->Renderer, temp_surf);
energyRECT.x = E_Mid_Coord.x - (energyRECT.w / 2);
energyRECT.y = E_Mid_Coord.y - (energyRECT.h / 2);
SDL_FreeSurface(temp_surf);
}
我已经初始化了所有SDL库,所以这应该不是问题所在。渲染器不会在更新之间消失。 临时表面被声明并定义每次更新,因此也应该没问题。
为什么这个功能导致我的游戏崩溃?
答案 0 :(得分:0)
你确定崩溃不在上一行吗?
if(!balanceTEXT){
SDL_DestroyTexture(balanceTEXT);
}
您似乎想要销毁NULL
指针
答案 1 :(得分:0)
我认为它可能是带有NULL指针的东西。也许在SDL_CreateTextureFromSurface调用之前检查显示对象指针。
答案 2 :(得分:0)
我发现了我的问题。第一次调用update函数是在类的构造函数中。此构造函数将screen*
对象作为参数。我调用了参数display
。但是,该类本身也有一个screen*
变量display
。
所以第一次使用参数display
,它有一个值,但第二次使用了类变量display
,我忘了定义。我将参数更改为DP
并将display = DP
添加到构造函数中。