c - What is the best way to find out why I'm getting a segmentation fault from traversing a linked list? -
i trying find out , need determining why program gets segmentation fault in main:
int main (void){ lista_conti *p = createlist(); conto c = malloc(sizeof(conto)); c->nome="uno"; c->predecessore=null; c->costo=0; c->visited=0; insert(p,c); printf("\n%d\n", isempty(p)); conto con =p->conto; char *nome = con->nome; /*segmentation fault*/ } here full listing of program, including main noted above.
/my struct/
typedef struct lista_conti{ void* conto; struct lista_conti *succ, *prec; }lista_conti; typedef struct{ char *nome; lista_conti *predecessore; /*valore hash(nome) del predecessore*/ int costo; int visited; /*0 false 1 true*/ }*conto; lista_conti *createlist (void){ lista_conti *q = malloc(sizeof(lista_conti)); if(!q) { fprintf(stderr,"errore di allocazione nella creazione della lista\n"); exit(-1); }; q->succ = q->prec = q; return q; } /*gli passo il puntatore alla testa della lista*/ int isempty(lista_conti *p){ if(p == null) return 1; else return 0; } /print full list/
void printlist(lista_conti *p){ lista_conti *r; r=p; if(r==null) { printf("no element in list :"); return; } /* traverse entire linked list */ while(r!=null) { conto cnt = r->conto; printf(" -> %s ",cnt->nome); r=r->succ; } printf("\n"); } /* insert element in head */
void insert(lista_conti *p, void* c){ printf("nella funzione insert"); if(isempty(p) == 1){ printf("\nlista vuota\n"); p->conto = c; p->succ=null; } lista_conti *q = malloc(sizeof(lista_conti)); if(!q) { fprintf(stderr,"errore nell'allocazione del nuovo elemento\n"); exit(-1); }; q->conto = c; q->succ = p->succ; p->succ->prec = q; p->succ = q; q->prec = p; } /* insert element in tail. */
void insertatend(lista_conti *p, conto c){ lista_conti *q = malloc(sizeof(lista_conti)); if(!q) { fprintf(stderr,"errore nell'allocazione del nuovo elemento\n"); exit(-1); }; q->conto = c; q->prec = p->prec; p->prec->succ = q; p->prec = q; q->succ = p; } int main (void){ lista_conti *p = createlist(); conto c = malloc(sizeof(conto)); c->nome="uno"; c->predecessore=null; c->costo=0; c->visited=0; insert(p,c); printf("\n%d\n", isempty(p)); conto con =p->conto; char *nome = con->nome; /*segmentation fault*/ } after insert, when try access con->nome, program return me segmentation fault. don't know why. there problem when create list? when insert?
upon initialization of list, create first node uninitialized conto field.
after inserting new node, original first node remains intact, when you're trying dereference p->conto cause segmentation fault.
the right way of creating doubly linked list having struct holds head , tail (you add count if like); they're both initialized null.
inserting updates head, appending updates tail.
Comments
Post a Comment