Segmentation fault initializing SDL2. What am I doing wrong with memory?

守給你的承諾、 提交于 2019-12-24 10:55:49

问题


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 EDIT: 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;
}

回答1:


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.

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:

  • Determine the line of C code that causes a segmentation fault?
  • http://www.cprogramming.com/debugging/segfaults.html

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



来源:https://stackoverflow.com/questions/41946389/segmentation-fault-initializing-sdl2-what-am-i-doing-wrong-with-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!