Code:
#include <stdio.h>
#include <stdlib.h>
void traverse(void);
/* Structure for printing the id.txt file */
struct id_card {
int ID;
struct id_card *nextptr;
};
typedef struct id_card node;
void traverse(void) {
FILE *fp;
node *newptr = NULL, *currptr = NULL;
int NUM, i, j=0;
int NUM_2 = 6;
newptr= (node*)malloc( sizeof(node) );
fp = fopen( "id.txt","r" );
if(fp == NULL) {
printf( "Unabale to open id.txt file \n" );
exit( 1 );
}
currptr = newptr;
for(i = 1; i<=8; i++) {
NUM = getc( fp );
NUM = NUM-48;
/*!! this is the problem - newptr isn't pointing at a valid node */
/*!! so trying to dereference it is a bad idea */
/*!! you've got to malloc a node before trying to store data in it */
newptr->ID = NUM;
printf( "%d",NUM );
newptr->nextptr=malloc( sizeof(node) );
newptr=newptr->nextptr;
}
if(newptr != NULL) {
newptr->ID = NUM_2;
newptr->nextptr=currptr;
currptr=newptr;
} else {
printf( "\n %d not inserted. No memory available.\n",NUM_2 );
}
do {
j++;
printf( "\n" );
printf( "%d", currptr->ID );
currptr=currptr->nextptr;
}
while(j<=8);
fclose( fp );
}