简体   繁体   中英

Linux, C, ncurses: seg fault caused by printw

Is there any reason why printw() would cause a segmentation fault?

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:

#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.

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. :-)

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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