Reputation: 3698
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:
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();
}
Upvotes: 1
Views: 746
Reputation: 141658
This causes undefined behaviour:
WINDOW *terrain;
// ...
wrefresh(terrain);
because you use an uninitialized variable. Take out the wrefresh(terrain)
line. 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);
Upvotes: 1