C ncurses: 在另一个函数中创建 WINDOW

C ncurses: Create WINDOW in another function

我是 ncurses 的新手,对 C 很生疏,所以我想对此有一个简单的解释。我想要一个 WINDOW 作为结构的 属性 并将其传递给其他函数。但是每次我在函数外使用 WINDOW 时,都会出现分段错误。

test1是我的理想,但我会尽力而为。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <ncurses.h>

struct Program {
    WINDOW *window;
};

struct Program *Program_create() {  
    struct Program p, *program = &p;
    program->window = newwin(10, 10, 0, 0);
    return program;
}

void sanity();
void test1();
void test2();
void test3();

int main(/* int argc, char *argv[]*/) {
    initscr();
    noecho();

    //sanity(); // creates box no problem
    //test1(); // Segmentation fault (core dumped)
    //test2(); // Segmentation fault (core dumped)
    //test3(); // creates box no problem

    endwin();
    return EXIT_SUCCESS/* 0 */;
}

void sanity() {
    WINDOW *window = newwin(10, 10, 0, 0);
    box(window, 0, 0);
    wrefresh(window);
    wgetch(window);
}

void test1() {
    struct Program *program = Program_create();
    box(program->window, 0, 0);
    wrefresh(program->window);
    wgetch(program->window);
}

void test2() {
    struct Program p, *program = &p;
    program = Program_create();
    box(program->window, 0, 0);
    wrefresh(program->window);
    wgetch(program->window);
}

void test3() {
    struct Program p, *program = &p;
    program->window = newwin(10, 10, 0, 0);
    box(program->window, 0, 0);
    wrefresh(program->window);
    wgetch(program->window);
}

struct Program *Program_create() {  
    struct Program p, *program = &p;
    program->window = newwin(10, 10, 0, 0);
    return program;
}

段错误的原因:这里,结构体实例p是一个局部变量。在我们从函数中 return 之后,这个结构实例 (p) 被删除。指针 program 指向一些无效数据。 program 变成悬空指针。

解决方案:在堆中分配内存,使用malloc

struct Program *Program_create() {  
        struct Program *program = malloc(sizeof(struct Program));
        program->window = newwin(10, 10, 0, 0);
        return program;
    }