简体   繁体   English

Linux,C,ncurses:由printw引起的段错误

[英]Linux, C, ncurses: seg fault caused by printw

Is there any reason why printw() would cause a segmentation fault? 有什么原因导致printw()会导致分段错误?

Code is fine without it; 没有它,代码就可以了。 broken with it. 坏了。 It doesn't seem to be doing anything esoteric, so I'm not sure how to even begin to understand what is wrong here. 它似乎并没有做任何深奥的事情,所以我不确定如何开始理解这里的错误所在。

Thanks in advance for any advice! 在此先感谢您的任何建议!

#include <ncurses.h>
...
initscr();
noecho();
cbreak();
...
    void draw_court()
    {
        move(TOP_ROW-1, LEFT_COL+4);
        printw("LIVES REMAINING: 3");

        int i;
        for (i = 0; i < RIGHT_COL; i++)
            mvaddch(TOP_ROW, LEFT_COL+i, H_LINE);

        for (i = 1; i < BOT_ROW-TOP_ROW; i++)
            mvaddch(TOP_ROW+i, LEFT_COL, V_LINE);

        for (i = 0; i < RIGHT_COL; i++)
            mvaddch(BOT_ROW, LEFT_COL+i, H_LINE);
    }

ETA: The stacktrace from gdb: ETA:来自gdb的stacktrace:

#0 0xb778a139 in _nc_printf_string () from /lib/libncurses.so.5
#1 0xb7785e04 in vwprintw () from /lib/libncurses.so.5
#2 0xb7785f63 in printw () from /lib/libncruses.so.5
#3 0x08048f23 in draw_court ()
#4 0x080489f4 in set_up ()
#5 0x0804890a in main ()

您是否忘了调用initscr ()?

Your best option is probably to run the code under gdb or another debugger, so you can see exactly what it's doing. 最好的选择可能是在gdb或其他调试器下运行代码,因此您可以确切地看到它在做什么。

If that's not an option, check your indices for off-by-one errors, and then try commenting out portions of the (entire) program until you've arrived at the smallest snippet that still crashes; 如果不是这种选择,请检查索引中是否存在一一错误,然后尝试注释掉整个程序的各个部分,直到找到仍然崩溃的最小代码段为止。 then post that if you'd like help debugging. 然后发布,如果您想帮助调试。

Also, because I can't help myself, you need only 2 loops to draw a box. 另外,由于我无法帮助自己,因此只需要2个循环即可绘制一个框。 :-) :-)

void draw_box()
{
    move(TOP_ROW-1, LEFT_COL+4);
    printw("LIVES REMAINING: 3");

    int i;
    for (i = 0; i < RIGHT_COL; i++) {  // should the limit be RIGHT_COL - LEFT_COL ?
        mvaddch(TOP_ROW, LEFT_COL+i, H_LINE);
        mvaddch(BOT_ROW, LEFT_COL+i, H_LINE);
    }
    for (i = 1; i < BOT_ROW-TOP_ROW; i++) {
        mvaddch(TOP_ROW+i, LEFT_COL, V_LINE);
        mvaddch(TOP_ROW+i, RIGHT_COL, V_LINE);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM