c - fscanf 正在崩溃程序

标签 c sdl

我正在做一个小项目,我想知道为什么这段代码会导致我的程序崩溃。

PLAYER_FILE_PATH -- "player.txt"

sprite=yoshi.bmp
width=64
height=64
frames=8
alignment=1
animate=1

程序

      FILE *pfile = fopen(PLAYER_FILE_PATH, "r");
if (!pfile)
{
    debug_printf("could not open player file for reading!\n");
    return;
}
fscanf(pfile, "sprite=%s\n\
               width=%d\n\
               height=%d\n\
               frames=%d\n\
               alignment=%d\n\
               animate=%d",
               player_entity.entity_sprite.imgloc,
               &player_entity.entity_sprite.width,
               &player_entity.entity_sprite.height,
               &player_entity.entity_sprite.frames,
               &player_entity.entity_sprite.oscdir,
               &player_entity.entity_sprite.osc);
fclose(pfile);

最佳答案

我们需要查看您对 player_entity 的定义才能确定。您可能没有正确定义“imgloc”,它需要指向一些安全分配的内存。例如,除非正确初始化 imgloc,否则以下定义​​将进行核心转储:

struct {
  struct {
    char *imgloc;
    int width;
    int height;
    int frames;
    int oscdir;
    int osc;
  } entity_sprite;
} player_entity;

如果你用类似的东西替换上面的 imgloc 行,这个核心转储将被避免

char imgloc[100];

但是,我会非常小心地使用 fscanf 读取字符串,因为如果字符串太长,它会溢出给定的缓冲区。也许只对字符串部分尝试 fgets,对其余部分尝试 fscanf。

关于c - fscanf 正在崩溃程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874581/

相关文章:

c中字符串与字符数组的比较

sdl - 编写更好的游戏循环

c++ - 尽管包含正确的文件,但未在此范围内声明

c++ - 指向 SDL 音频回调的成员函数的指针?

sdl - 使用 SDL 制作 2d 灯光效果

循环遍历文本文件并捕获字符串值

c - 一些带有指针的 'predict the outputs'

c - 加载共享库时出错,无法打开共享对象文件 : No such file or directory (hiredis)

由变量给出的 C 数组大小

android - 将 WebOS SDL + SDL_Mixer 应用程序移植到 Android 的选项有哪些