ncurses 分段错误

ncurses Segmentation Fault

我正在修改一个项目的代码,该项目有人使用 ASCII 艺术圆环完成,称为 donut.c。我觉得有必要在面向对象的范例中使用该程序中的代码绘制其他三维形状,但也想对其进行修改以使其 运行 在多个平台上运行。我选择将 C++ 与 ncurses 一起使用,以便可以在 Windows、Linux 和 Mac 上使用该库。但是,我 运行 我的代码出现了一个错误:分段错误一直发生在我代码的一个非常特定的部分,我不知道该从哪里着手解决这个问题。

我获取代码(在下面找到)并使用 g++ -Wall -g test.cc -o test -lncurses 编译它,这样我们就可以使用 gdb 找出问题所在。这是那次遭遇的输出:

(gdb) watch test == 3030
Hardware watchpoint 1: test == 3030
(gdb) r
Hardware watchpoint 1: test == 3030

Old value = 0
New value = 1
main (argc=1, argv=0xbffff1d4) at test.cc:38
38          Output(output, screen_height, screen_width);
(gdb) step
Output (
  output=0xbfffe958 ' ' <repeats 28 times>, "$$@@@@@@", '$' <repeats 15 times>, ' ' <repeats 54 times>, '$' <repeats 11 times>, '#' <repeats 13 times>, "$$$##", ' ' <repeats 48 times>, "##$$$$#$####******"..., screen_height=24, 
screen_width=80) at test.cc:91
91        printw(output)
(gdb) step
Program received signal SIGSEGV, Segmentation fault.
__wcslen_sse2 () at ../sysdeps/i386/i686/multiarch/wcslen-sse2.S:28
28      ../sysdeps/i386/i686/multiarch/wcslen-sse2.S: No such file or directory.

test 变量设置到我知道的第 3030 帧的位置,它会出错。有趣的是,如果 screen_widthscreen_height 值发生变化,发生分段错误的“帧”仍然相同。我相信我的 ncurses 库是最新的,因为我专门安装它来处理这个项目(2017 年 2 月 1 日)。

这是我的 C++ 代码,对原始 donut.c 进行了修改并经过编辑以仅适合被认为相关的代码。

static volatile int test = 0; //used for checking what frame it happened at

void Output(char* output, int screen_height, int screen_width); //where segfault happens
void RenderFrame(float x_rotation, float z_rotation, char* output, float* zbuffer, int screen_height, int screen_width);

int main(int argc, const char **argv)
{ 
  //Initialization completed. Note that I call initscr() and necessary methods before
  while(getch() == ERR)
  {
    RenderFrame(x_rotation, z_rotation, output, zbuffer, screen_height, screen_width);
    test++;
    Output(output, screen_height, screen_width);
    x_rotation += x_rotation_delta;
    z_rotation += z_rotation_delta;
  }
  endwin();

  return 0;
}

void Output(char* output, int screen_height, int screen_width)
{
  printw(output);
  refresh();
  move(0, 0);
}

TL;DR

ncursesprintw 有问题,导致 Segmentation fault。我该如何解决这个问题或绕过它,以便我可以让它正常工作。更重要的是,这是 ncurses 还是我的代码的问题?

问题如 Thomas Dickey 在他对问题的评论中所述:我需要在代码中将 printw 更改为 addstr。谢谢大家的建议,我仍然很好奇为什么 printw.

会发生这种情况