SDL系统内存在我的游戏中增长得非常非常快

SDL system memory rising very very fast on my game

本文关键字:非常 游戏 系统 内存 存在 我的 SDL      更新时间:2023-10-16

这是我的代码:

void apply_start_screen()
{
apply_surface( 0, 0, startingScreenBackground, screen );
apply_surface( ( SCREEN_WIDTH - startButton->w ) /2, 200, startButton, screen);
apply_surface( ( SCREEN_WIDTH - infoButton ->w ) /2, 450, infoButton, screen );
message = TTF_RenderText_Solid( font, "In The Jungle!", green );
apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 25, message, screen );
SDL_Flip( screen );
 }

主代码。。。

Mouse start( ( SCREEN_WIDTH - startButton->w ) /2,  200, 200, 200);

这个类只使用sdl-rect创建一个按钮,并检查它是否被按下

以及这里的问题:

while( quit == false )
{
    apply_start_screen();
if( start.handle_event() == true )
{
    currentState = 1;
}
}

当前状态只是转到下一个屏幕,不用担心。问题是apply_start_screen()每次使用都会使系统内存增加。我不明白。如果你多次渲染相同的图像/文本,会占用更多的内存吗?为什么?sdl曲面是动态分配的,但我仍然渲染相同的曲面,这意味着我不会分配更多的内存?有什么建议吗?谢谢你抽出时间。

解决方案:由于TTF_RenderText_Solid返回一个曲面,而SDL_surface是一个动态分配像素的结构,所以问题是在的每一帧上,apply_start_screen函数都在动态分配内存。有两种方法可以解决此问题:首先创建一个全局SDL_surface*消息,并执行以下操作:

void apply_start_screen()
{
apply_surface( 0, 0, startingScreenBackground, screen );
apply_surface( ( SCREEN_WIDTH - startButton->w ) /2, 200, startButton, screen);
apply_surface( ( SCREEN_WIDTH - infoButton ->w ) /2, 450, infoButton, screen );
message = TTF_RenderText_Solid( font, "In The Jungle!", green );
apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 25, message, screen );
    SDL_FreeSurface( message );
    message = NULL;
 }

或者简单地删除TTF_RendeText_Solid,这样就不会再创建/返回曲面,如下所示:

void apply_start_screen()
{
apply_surface( 0, 0, startingScreenBackground, screen );
apply_surface( ( SCREEN_WIDTH - startButton->w ) /2, 200, startButton, screen);
apply_surface( ( SCREEN_WIDTH - infoButton ->w ) /2, 450, infoButton, screen );
apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 25, message, screen );
}
    main...
    message = TTF_RenderText_Solid( font, "In The Jungle!", green );
    rest of program...

希望我能帮上忙:)