Thread: problem with segmentation fault

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    36

    problem with segmentation fault

    Hi..everyone..i had trying to solve this problem but i really can't because i don't have any experience with C core dumped.Below is a program that can be compile but after exceution i get Segmentation fault (core dumped) with gcc (cygwin) compiler. Can anyone give me some piece of advice or tips.Thanks alot.
    Code:
    typedef struct bookStruct
    {
       int id;
       char title[TITLE_LEN + 1];
       char author[AUTHOR_LEN + 1];
       int year;
       float price;
       int count;
       struct bookStruct* next;
    } BookType;
    
    typedef struct bookListStruct
    {
       BookType* head;
       int count;
    } BookListType;
    
    BookType *b;
     
    /* Function prototypes. */
    
    void loadData(BookListType*, char*);
    void displayBooks(BookListType*);
    
    //int main(void)
    int main(int argc, char *argv[])
    {
     BookListType* booklist;
     int i;
     FILE *bookRead;
     char line[LINESIZE] , *word;
     
     if ( argc != 2 ) 
     {
        fprintf ( stderr, "Usage: %s <readfile1>\n", argv[0] );
        exit ( EXIT_FAILURE );
     }
      if((bookRead = fopen( argv[1], "r" )) == NULL)
     {
      fprintf(stderr, "cat: can't open %s\n", argv[1]);
     }
      
      loadData(booklist, argv[1]);
      displayBooks(booklist);
      fclose ( bookRead );
      return EXIT_SUCCESS;
    }
    
    void loadData(BookListType* booklist, char* booksFile)
    {   
       char *delimeter = ":";
       char  *token, *bookPtr;
       char bookWord[100];
       BookType *b;
       FILE *bfile;
    	/* fopen opens the file; exits if file cannot be opened */
    	
    	if ( ( bfile = fopen( booksFile, "r" ) ) == NULL ) 
    	{
    		fprintf(stderr,"***> Open error reading input file %s", booksFile);
    		exit(-1);
    	} 
    	/* read all records from file (until eof) */
    	while(!feof(bfile))
    	{
    	  while (bookPtr != NULL)
    	   {
            if(fgets(bookWord,sizeof(bookWord),bfile)!=NULL) 
            {
     	      if (b = (BookType*)malloc(sizeof(BookType)))
               {   
                /*	copy the data from BookType to linked list	*/ 
                bookPtr = strtok(bookWord,delimeter);
                b->id=atoi(bookPtr);
    		    strcpy(b->title, bookPtr);
    		    strcpy(b->author, bookPtr);
    		    b->year = atoi(bookPtr);
    		    b->price = atof(bookPtr);
    		    b->count = atoi(bookPtr);
                }
                bookPtr = strtok(NULL, delimeter);
             }    
                b->next = booklist->head;
                booklist->head = b;
                booklist->count++;       
    	     }
            }
    	fclose(bfile);
    }
    void displayBooks(BookListType* booklist)
    {
         printf("ID  Title\t\t\t    Author\t Year\tPrice\tCount\n");
    	printf("--  -----------------------------   ------------ ----\t-------\t-----\n");
    
    	while(booklist->head!=NULL)
    	{
    		printf("%2d  %-32s%-12s%6d\t%2c%5.2f\t%4d\n", booklist->head->id,
    			booklist->head->title, booklist->head->author, booklist->head->year,'$', 
    			booklist->head->price,booklist->head->count);
    		booklist->head = booklist->head->next;
    	}
    }
    Last edited by cBegginer; 05-14-2005 at 09:33 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define TITLE_LEN 20
    #define AUTHOR_LEN 40
    #define LINESIZE 300
    
    typedef struct bookStruct {
        int id;
        char title[TITLE_LEN + 1];
        char author[AUTHOR_LEN + 1];
        int year;
        float price;
        int count;
        /*SaleType *head;*/
        struct bookStruct *next;
    } BookType;
    
    typedef struct bookListStruct {
        BookType *head;
        int count;
    } BookListType;
    
    /* unused - same name as a local variable */
    /* BookType *b; */
    
    /* Function prototypes. */
    
    void loadData(BookListType *, char *);
    void displayBooks(BookListType *);
    
    int main(int argc, char *argv[])
    {
        BookListType *booklist /* = NULL   uninitialised!! */;
        /*int i; is unused */
        FILE *bookRead;
        /*char line[LINESIZE], *word; is unused */
    
        if (argc != 2) {
            fprintf(stderr, "Usage: %s <readfile1>\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        if ((bookRead = fopen(argv[1], "r")) == NULL) {
            fprintf(stderr, "cat: can't open %s\n", argv[1]);
        }
    
        /*!! calling this doesn't modify booklist in this scope */
        /* Try something like   booklist = loadData(argv[1]); */
        loadData(booklist, argv[1]);
        displayBooks(booklist);
        fclose(bookRead);
        return EXIT_SUCCESS;
    }
    
    void loadData(BookListType * booklist, char *booksFile)
    {
        char *delimeter = ":";
        char /* unused *token, */ *bookPtr;
        char bookWord[100];
        BookType *b;
        FILE *bfile;
        /* fopen opens the file; exits if file cannot be opened */
    
        if ((bfile = fopen(booksFile, "r")) == NULL) {
            fprintf(stderr, "***> Open error reading input file %s",
                    booksFile);
            exit(-1);
        }
        /* read all records from file (until eof) */
        while (!feof(bfile)) {  /*!! see the FAQ */
            while (bookPtr != NULL) { /* !! bookPtr starts off uninitialised */
                if (fgets(bookWord, sizeof(bookWord), bfile) != NULL) {
                    /*!! don't cast malloc in C */
                    if (b = (BookType *) malloc(sizeof(BookType))) {
                        /*  copy the data from BookType to linked list  */
                        bookPtr = strtok(bookWord, delimeter);
                        b->id = atoi(bookPtr);
                        strcpy(b->title, bookPtr);
                        strcpy(b->author, bookPtr);
                        b->year = atoi(bookPtr);
                        b->price = atof(bookPtr);
                        b->count = atoi(bookPtr);
                    }
                    bookPtr = strtok(NULL, delimeter);
                }
                b->next = booklist->head;
                booklist->head = b;
                booklist->count++;
            }
        }
        fclose(bfile);
    }
    
    void displayBooks(BookListType * booklist)
    {
        printf("ID  Title\t\t\t    Author\t Year\tPrice\tCount\n");
        printf("--  -----------------------------   ------------ ----\t-------\t-----\n");
    
        while (booklist->head != NULL) {
            printf("%2d  %-32s%-12s%6d\t%2c%5.2f\t%4d\n", booklist->head->id,
                   booklist->head->title, booklist->head->author,
                   booklist->head->year, '$', booklist->head->price,
                   booklist->head->count);
            booklist->head = booklist->head->next;
        }
    }
    There are many things wrong - mostly concerned with uninitialised pointers. These usually draw a segfault when you try and dereference them.

    Something else to consider, try and simplify the code by not trying to do too much in a single function.
    For example
    Code:
    BookType *ConvertData( char *buff ) {
        BookType *node = malloc ( sizeof *node );
        if ( node ) {
            /* do whatever to extract data */
            sscanf( buff, "%d", &node->id );
        }
        return node;
    }
    
    BookListType *booklist loadData ( char *booksFile ) {
        BookListType *result = NULL;
        char buff[BUFSIZ];
        FILE *fp = fopen( booksFile, "r" );
        while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
            BookType *node = ConvertData( buff );
            result = ListAppend( result, node );
        }
    }
    Each function does one specific task.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    I just wanted to see if I could do this, I'm posting this code because it may help you, but I can't explain anything because I'm too tired, though the comments are helpful.

    Replace ASSERT with
    Code:
    #include <assert.h>
    assert( BLAH );
    Code:
    #define DEBUG 1
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <al/etl.h>
    #include <sfl.h>
    
    
    struct sb
    {
    	int id;
    	int year;
    	int count;
    	char title[NAME_MAX];
    	char author[NAME_MAX];
    	float price;
    	struct sb* next;
    };
    
    
    /* BOOK MANAGEMENT */
    typedef struct
    {
    	struct sb* begin;
    	struct sb* now;
    	int count;
    } BManager;
    
    
    /* Function prototypes. */
    void loadData( BManager *bmanager, char *booksFile );
    void displayBooks( BManager *bmanager );
    void getBookAttribute( char *delimiter, char *ZtoWhere, int *NtoWhere, float *FtoWhere );
    
    
    /* MAIN!!! */
    int main( int argc, char *argv[] )
    {
    	/* VARs */
    	BManager bmanager;	
    	
    	/* Validate arguments */
    	ASSERT( argc == 2 );
    	
    	/* Load the books from text data source */
    	loadData( &bmanager, *++argv );
    	
    	/* Display the books */
    	displayBooks( &bmanager );
    
    	/* EXIT Success! */
    	return EXIT_SUCCESS;
    }
    
    
    /* Get book attribute from book line */
    void getBookAttribute( char *delimiter, char *ZtoWhere, int *NtoWhere, float *FtoWhere )
    {
    	char *ptr;
    	
    	ASSERT( ( ptr = strtok( NULL, delimiter ) ) );
    	if( NtoWhere )
    	{
    		*NtoWhere = atoi( ptr );
    		printf( "Found: %d\n", *NtoWhere );
    	}
    	else if( FtoWhere )
    	{
    		*FtoWhere = atof( ptr );
    		printf( "Found: %f\n", *FtoWhere );
    	}
    	else if( ZtoWhere )
    	{	
    		strncpy( ZtoWhere, ptr, NAME_MAX );
    		printf( "Found: %s\n", ZtoWhere );
    	}
    }
    
    
    /* Load all of the books from the bookList */
    void loadData(BManager *bmanager, char *booksFile)
    {   
    	/* VARs */
    	char *delimiter = ":", *ptr;
    	char bookLine[LINE_MAX];
    	Bool firstBook = TRUE;
    	struct sb *b;
    	FILE *bfile;
    	
    	
    	/* fopen opens the file; exits if file cannot be opened */
    	ASSERT( ( bfile = fopen( booksFile, "r" ) ) );
    
    	/* Read from bfile */
    	while( fgets( bookLine, LINE_MAX, bfile ) )
    	{			
    		/* Create some room for a book */
    		ASSERT( ( b = malloc( sizeof( struct sb ) ) ) );
    		
    		/* Break down the bookline into attributes */
    		ASSERT( ( ptr = strtok( bookLine, delimiter ) ) );
    		b->id = atoi( ptr );
    		getBookAttribute( delimiter, b->title, NULL, NULL );
    		getBookAttribute( delimiter, b->author, NULL, NULL );
    		getBookAttribute( delimiter, NULL, &( b->year ), NULL );
    		getBookAttribute( delimiter, NULL, NULL, &( b->price ) );
    		getBookAttribute( delimiter, NULL, &( b->count ), NULL );
    		
    		/* Put the book into the bookManager */
    		if( firstBook )
    		{
    			firstBook = FALSE;
    			bmanager->now = b;
    			bmanager->begin = b;
    		}
    		else
    		{
    			bmanager->now->next = b;
    			bmanager->now = bmanager->now->next;
    		}
    		
    		bmanager->now->next = NULL;
    		bmanager->count++;
    	}
    	
    	/* Destroy the file pointer */
    	fclose( bfile );
    	bfile = NULL;
    }
    
    
    void displayBooks( BManager* bmanager )
    {
    	struct sb *aBook;
    
    	printf( "%2s %20s %16s %6s %6s %4s\n",
    		"ID",
    		"Title",
    		"Author",
    		"Year",
    		"Price",
    		"Count"
    		);
    	printf( "-----------------------------------------------------------\n");
    
    	bmanager->now = bmanager->begin;
    	while( bmanager->now )
    	{
    		printf( "%2d %20s %16s %6d  $%5.2f %4d\n", 
    			bmanager->now->id,
    			bmanager->now->title, 
    			bmanager->now->author, 
    			bmanager->now->year,
    			bmanager->now->price,
    			bmanager->now->count );
    			
    		aBook = bmanager->now;
    		bmanager->now = bmanager->now->next;
    		free( aBook );
    	}
    }

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    20
    I would like to ask if it so happens that the structure contains a date. How do you strtok it? For example:
    Code:
    #include <time.h>
    
    struct sb
    {
    	int id;
            struct tm date;
    	int count;
    	char title[NAME_MAX];
    	char author[NAME_MAX];
    	float price;
    	struct sb* next;
    };

  5. #5
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    No need to strtok(), you can use time_t, it's a long integer. So you can use atol() instead of strtok() to get the date. Example:

    Code:
    #include <time.h>
    #include <stdio.h>
    #include <al/etl.h>
    #include <sfl.h>
    
    /*
    Points of interest:
    - localtime() converts time_t* to struct tm*
    - ctime() is a quick way to turn *time_t into some readable output
    - strftime( char *putDateStuffInHere, int howManyCharactersCanGoInTheString,
    	const char *whatFormatDoYouWantMeToPutTheDateIn,
    	struct tm *giveMeADateToWorkWith )
    */
    
    int main( void )
    {
    	/* Get time from database & setup custom date output string */
    	time_t inDatabaseTime = time( NULL );
    	char anotherOutput[NAME_MAX];
    	
    	/* Setup the custom output */
    	strftime( anotherOutput, NAME_MAX, "%B %d, %Y", localtime( &inDatabaseTime ) );
    
    	/* Output the time */
    	printf( "Put this into your database: %ld\n", inDatabaseTime );
    	printf( "Give this to the user for output: %s", ctime( &inDatabaseTime ) );
    	printf( "Another user output: %s\n", anotherOutput );
    	
    	/* Exit success */
    	return EXIT_SUCCESS;
    }
    
    /*
    Output:
    Put this into your database: 1116122160
    Give this to the user for output: Sat May 14 18:56:00 2005
    Another user output: May 14, 2005
    */

  6. #6
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    hey thanks friends..i solve my problem..thanks alot..

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Kleid-0
    No need to strtok(), you can use time_t, it's a long integer.
    Don't assume too much. I would find too much wiggle room with "arithmetic type[s] capable of representing times".
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Registered User
    Join Date
    Mar 2005
    Posts
    20
    Sorry I am still a bit confused. Please bear with me, as I'm quite new to structures and dates. Given the following structure:
    Code:
    #include <time.h>
    
    struct sb
    {
    	int id;
            struct tm date;
    	int count;
    	char title[NAME_MAX];
    	char author[NAME_MAX];
    	float price;
    	struct sb* next;
    };
    How can I read from a file and store it into the structure? For example, file.dat contains this:
    Code:
    1:15/05/2005:5:C programming:C lovers:99.99
    2:03/05/2005:10:C pointers:C lovers:45.56
    I only know how to do tokenizing and storing into the structure if it does not involves the struct tm date.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Why not just
    char date[11];
    until you know what you need to do with date.

    If you want to convert it to struct tm, or anything else later on, then you can still do that.
    But for now, a string is good enough IMO
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Hey Dave,
    time_t is usually a long integer. But either way you'd probably still be using atol() to convert the string Unix timestamp to the long number that will be placed into a time_t variable (that will, I believe, be some sort of integer).

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    No - you use mktime() to create a time_t
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Kleid-0
    Hey Dave,
    time_t is usually a long integer. But either way you'd probably still be using atol() to convert the string Unix timestamp to the long number that will be placed into a time_t variable (that will, I believe, be some sort of integer).
    Usually is not always.
    Probably is not as good as a sure thing.

    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    But it's probably some type of integer. Ok I'm going to risk my life here...time_t is a type of integer, and thus we can use atol() from the database to move that string "9273278937" to a good ol' time_t variable, and thus create any date format string we want.

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Why would you even bother, given that there are routines to pack and unpack a time_t variable.
    Even if you assume it is an integral type, you still have to then assume that it contains seconds.

    The standard merely states that time_t is an arithmetic type.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 03:36 AM
  2. Strange segmentation fault
    By Ron in forum C Programming
    Replies: 24
    Last Post: 06-15-2008, 02:10 PM
  3. Segmentation Fault hmm?
    By pobri19 in forum C Programming
    Replies: 4
    Last Post: 05-03-2008, 07:51 AM
  4. Re: Segmentation fault
    By turkish_van in forum C Programming
    Replies: 8
    Last Post: 01-20-2007, 05:50 PM
  5. [C++] Segmentation Fault {Novice C++ Programmer}
    By INFERNO2K in forum C++ Programming
    Replies: 24
    Last Post: 06-08-2005, 07:44 PM