简体   繁体   English

Malloc结构 分段故障

[英]Malloc to struct; segmentation fault

So I defined my struct outside of any function: 所以我在任何函数之外定义了我的结构:

typedef struct limb{
    char c;
    struct limb *child;
    int x;
    int y;
}limb;

And tried to allocate memory to it: 并尝试为其分配内存:

limb *body;
body = malloc(sizeof(limb));
body->child = malloc(sizeof(limb));

But it gives me segmentation fault. 但这给了我分割错误。 Any help will be appreciated. 任何帮助将不胜感激。

gdb: GDB:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000409162 in wsyncdown ()
(gdb) x 0x0000000000409162
0x409162 <wsyncdown+18>:    0x406f8b48

Whole code (hope it helps): 整个代码(希望有帮助):

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

int max_x, max_y;

void welcome_screen();
void terrain();

typedef struct limb{
    char c;
    struct limb *child;
    int x;
    int y;
}limb;

int main()
{
    welcome_screen();
    terrain();
    return 0;
}
void terrain()
{
    WINDOW *terrain;
    int startx, starty, width, height;
    keypad(stdscr, TRUE);
    wrefresh(terrain);
    height = 60;
    width = 100;
    starty = (LINES - height) / 2;
    startx = (COLS - width) / 2;
    terrain = newwin(height, width, starty, startx);
    wborder(terrain, '|', '|', '-', '-', '+', '+', '+', '+');
    wrefresh(terrain);
    limb *body;
    if(!(body = malloc(sizeof(limb)))){
        printw("SEGMENTATION FAULT");
        getch();
    }
    /*body->child = malloc(sizeof(limb));*/


    while(1);
    endwin();
}

This causes undefined behaviour: 这会导致不确定的行为:

WINDOW *terrain;
// ...
wrefresh(terrain);

because you use an uninitialized variable. 因为您使用了未初始化的变量。 Take out the wrefresh(terrain) line. 取出wrefresh(terrain)线。 To avoid this sort of error you could delay declaring variables until you are ready to initialize them: 为了避免这种错误,您可以延迟声明变量,直到准备好初始化它们为止:

// ...
WINDOW *terrain = newwin(height, width, starty, startx);

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

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