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



我是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是一个局部变量。在我们从函数返回后,这个结构实例(p(将被删除。并且指针program指向一些无效数据。CCD_ 4变为悬空指针。

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

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

相关内容

  • 没有找到相关文章

最新更新