Hello, this is my first submission at this forum, hope you'll help ; )
I wrote this program to see if I knew how to manipulate linked lists:
It simply reads an integer 'n' from the keyboard and then generates a linked list with 'n' elements, with each element receiving, progressively, a number (from 0 to 'n') to "number". Then it prints each "number" and frees the allocated memory.Code:#include <stdio.h> #include <stdlib.h> typedef struct List { int number; struct Lista *next; } list; main () { int p, i; lista *begin, *new; inicio->prox = NULL; scanf("%d", &p); new = ( list * ) malloc( sizeof( list ) ); new->next = NULL; begin = new; for ( i = 0; i < p; i++ ) { new = ( list * ) malloc( sizeof( lista ) ); new->number = i; new->next = begin; begin = new; } while ( new->next != NULL ) { printf("%d\n", (*new).number); new = new->next; } for ( i = 0; i < p; i++ ) { new = begin; begin = begin->next; free(new); } return 0; }
When I try to compile it with gcc (I'm at a Fedora OS), it returns something like "Segmentation fault (kernel image recorded)" ("Falha de segmentacao (imagem do nucleo gravada).
Can you tell me what's wrong?
Thanks a lot!