Benuck
Benuck

Reputation: 19

C malloc segmentation fault struct

In the textbook my teacher provided us, there is this C code's sample, which when I try to run gives a Segmentation Fault error:

const celula *nulo = NULL;
typedef char informacao;
typedef celula *noh;
typedef celula *arvore;
struct celula {informacao info; noh pai; noh fesq; noh idir;};

...

typedef struct celfloresta celfloresta;
typedef struct celfloresta *floresta;
typedef struct celfloresta *posicfloresta;
struct celfloresta {arvore elem; celfloresta *prox;};

...

void FormarListaNohs(){
    floresta p = (floresta)malloc(sizeof(celfloresta));
    p->elem->info = '3';
}

...

Why does the line p->elem->info = '3'; give segmentation fault here?

Upvotes: 0

Views: 76

Answers (2)

medmik
medmik

Reputation: 1

Basically malloc return a void pointer then to cast is should use a variable of type pointer an example :

int *p = malloc(sizeof(int))
struct s_list *l = malloc(sizeof(struct s_list))

then you can dereference the pointer for example

l->data = 12;

Upvotes: 0

Saucy Goat
Saucy Goat

Reputation: 1675

elem is a pointer. You need to allocate memory for it:

p->elem = malloc(sizeof(arvore));

Upvotes: 2

Related Questions