本文介绍了初始化 SDL2 的分段错误.我的记忆有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是假设向 SDL 窗口前端缓冲区显示 bmp 图像.我玩弄代码.我认为我的 init() 函数有问题.我是 SDL 的新手.但是我的指针肯定有问题,或者我对 SDL 的功能遗漏了什么我使用了 GDB,结果我的 close() 函数是问题所在.我相信这是因为我正在释放设置为 NULL 的内存?我摆脱了关闭功能,并在延迟功能后释放了内存.

This is just suppose to display a bmp image to the SDL window front buffer. I played around with the code. And I think there is something wrong with my init() function. I'm new to SDL. But there must be a problem with my pointers or something I'm missing about SDL's fucntions I used GDB and it turned out my close() function was the problem. I believe it was because I was freeing memory that was set to NULL? I got rid of the close fucntion and just freed mem after my delay function.

#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdbool.h>
#define SCREENWIDTH 640
#define SCREENHEIGHT 480
SDL_Window *win = NULL;
SDL_Surface *scrn = NULL;
SDL_Surface *mscrn = NULL;
bool init()
{
   bool suc = true;
   char name[11] = "Hello SDL";
   if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    printf("%s", SDL_GetError());
    suc = false;
   }
  win = SDL_CreateWindow(name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREENWIDTH, SCREENHEIGHT, SDL_WINDOW_SHOWN);
  if (win == NULL) {
    printf("%s", SDL_GetError());
    suc = false;
  }
scrn = SDL_GetWindowSurface(win);

return suc;
}
bool loadmedia()
 {
   bool suc = true;
   mscrn = SDL_LoadBMP("hello_world.bmp");
   if (mscrn == NULL) {
   printf("%s", SDL_GetError());
   suc = false;
  }
   return suc;
}
void close()
{
  SDL_FreeSurface(mscrn);
   SDL_DestroyWindow(win);
   SDL_Quit();
}
int main(int argc, char* args[])
{
 if (!init()) {
   close();
   return 1;
  }
  if (!loadmedia()) {
   close();
   return 1;
  }
   SDL_BlitSurface(mscrn, NULL, scrn, NULL);
   SDL_UpdateWindowSurface(win);
   SDL_Delay(3000);

   close();
   return 0;
}

推荐答案

您应该找到合理的调试器和其他工具来找出导致错误的行以及原因.基本上,它归结为使用调试器(如果您正在使用 IDE 时通常随同您的 IDE 一起使用),或者使用非常好的代码分析工具 Valgrind.

You should find a reasonable debugger and other tools to to find out which line is causing the error and why. Basically it boils down to using a debugger which usually comes with your IDE if you're using one, or using the very good code analysis tool, Valgrind.

如果您使用 gcc,您可能可以使用 gdb 轻松调试您的程序.以下是一些有关如何帮助您诊断分段错误的资源:

If you're using gcc you can likely use gdb to debug your program easily. Here are some resources on how to help you diagnose segmentation faults:

熟悉这些工具,因为它们将在您未来遇到新问题时为您节省无数时间.

Get familiar with these tools, as they will save you countless hours in the future when you face new problems.

这篇关于初始化 SDL2 的分段错误.我的记忆有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:52