0

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?

4
  • 2
    Need to malloc memory for elem too. Commented Dec 17, 2019 at 19:13
  • regarding: const celula *nulo = NULL; This is using the celula before it is defined. Suggest moving that statement to after the definition of the struct Commented Dec 18, 2019 at 4:14
  • OT: regarding: floresta p = (floresta)malloc(sizeof(celfloresta)); 1) in C, the returned type is void* which can be assigned to any pointer. Casting just clutters the code. Suggest removing the cast. 2) always check (!=NULL) the returned value to assure the operation was successful. Commented Dec 18, 2019 at 4:16
  • OT: regarding: typedef struct celfloresta *floresta; and typedef struct celfloresta *posicfloresta; and typedef celula *noh;` and typedef celula *arvore; It is a very poor programming practice (and very misleading to the human reader of the code) to hide pointers in a typedef. Commented Dec 18, 2019 at 4:19

2 Answers 2

2

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

p->elem = malloc(sizeof(arvore));
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.