ncurses 不断给 SIGSEGV

问题描述

我对 C 和 ncurses 有点陌生,我会尝试我学到的东西以确保我理解它。我正在从 here 学习 ncurses,从 here 学习 C,但我选择不从那本 C 书中学习 GTK,因为我对前端开发不感兴趣。我试图在 ncurses 中尝试使用 mvprintw 函数,但没有奏效。在 gdb 中运行它显示

This program will print a letter on whatever coordinates you want
Enter an x coordinate: 2
Enter a y coordinate: 3
Enter the letter to print: 
                           Program received signal SIGSEGV,Segmentation fault.
                                                                               strlen () at ../sysdeps/arm/armv6/strlen.S:26
26  ../sysdeps/arm/armv6/strlen.S: No such file or directory.
(gdb) quit
A debugging session is active.

    Inferior 1 [process 7659] will be killed.

Quit anyway? (y or n) n
Not confirmed.
(gdb) c
Continuing.

Program terminated with signal SIGSEGV,Segmentation fault.
The program no longer exists.
(gdb)

据我所知,SIGSEGV 表示我访问了内存的受限部分。我是如何做到这一点的,我该如何防止这种情况发生?这是我的代码

#include <stdio.h>
#include <ncurses.h>

int main(int argc,char *argv[]){
  // initialize ncurses
  initscr();
  // stop echoing
  noecho();
  printw("This program will print a letter on whatever coordinates you want\nEnter an x coordinate: ");
  refresh();
  // set 'x' to the user input
  char x = getch();
  printw("%c\n",x);
  refresh();
  printw("Enter a y coordinate: ");
  refresh();
  // set 'y' to the user input
  char y = getch();
  printw("%c\n",y);
  refresh();
  printw("Enter the letter to print: ");
  // set input as letter
  char word = getch();
  printw("%s",word);
  refresh();
  // mvprintw(y,x,"%s",word);
  // refresh();
  // getch();
  // endwin();

  return 0;
}

(我取消了最后几行的注释,因为那不是发生错误的地方)

解决方法

  char word = getch();
  printw("%s",word);

错了。正如您在之前的几行中所做的那样,您应该使用 %c 而不是 %s 来打印一个字符。