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?
mallocmemory forelemtoo.const celula *nulo = NULL;This is using thecelulabefore it is defined. Suggest moving that statement to after the definition of the structfloresta p = (floresta)malloc(sizeof(celfloresta));1) in C, the returned type isvoid*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.typedef struct celfloresta *floresta;andtypedef struct celfloresta *posicfloresta;and typedef celula *noh;` andtypedef celula *arvore;It is a very poor programming practice (and very misleading to the human reader of the code) to hide pointers in atypedef.