Thread: Segmentation Fault

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    7

    Segmentation Fault

    Hi everyone,

    Just a bit of a hand with a problem thats been driving me up the wall of late if anyone would be so kind, if been set a problem of reading in 2 external csv files into my C prog and holding them both in arrays before doing various calculations on them. Ive managed to almost get the first file read in but keep getting a segmentation error, ive a pretty good idea of where its happening but try as i might i cant seem to crack it. I'll post the prog i have so far below and any help in pointing me in the right direction would be appreciated

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    typedef struct {
    	int year; // year for which data exists
    	double pop; // Population that year (in millions)
    	double bot;
    	double botPerHead;
    } Data;
    
    typedef struct {
    	char countryName[50]; // maximum length of name
    	char countryCode[4]; // UN assigned 3 character country code
    	Data yearlyData[11]; // max. 12 year’s data (1995 – 2006)
    } Country;
    
    
    int main(void)
    {
    
    	FILE *fppop;
    	FILE *fpbot;
    	Country countries[250];
    	int i = -1;
    	int dataYear;
    	char input[1500];
    	char *p;
    	char previousName[50] = "";
    
    	// read in pop file
    
    	fppop = fopen("un-country-pop.csv", "r");
    
    	if (fppop == NULL) {
    		puts("Error opening file");
    		exit(EXIT_FAILURE);
    	}
    
    	while (!feof(fppop)) {
    
    		fgets(input, 1500, fppop);
    
    		if (input[0] == '#')
    			continue;
    
    		p = strtok (input,",");
    
    		if (strcmp(p, previousName) != 0) {
    			// first time we've seen this country
    			i++;
    			// copy country name to countries[i].
    			strcpy(previousName, p);
    		}
    
    		strcpy(countries[i].countryName, p);
    		p = strtok (NULL,",");
    		strcpy(countries[i].countryCode, p);
    		strtok(NULL,",");
    		strtok(NULL,",");
    		strtok(NULL,",");
    
    // im pretty sure the segmentation fault is happening here as im not quite sure how to assign the year and population values to the array within an array
    
    		p = strtok(NULL,","); // year string
    		dataYear = atoi(p);
    		countries[i].yearlyData[2006 - dataYear].year = atoi(p);
    		//p = strtok(NULL,","); //pop
    		//countries[i].yearlyData[2006 - dataYear].pop = atof(p);
    	}
    	printf("%d\n",i);
    
    }

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Firstly

    Code:
    fgets(input, 1500, fppop);
    Is the same as;
    Code:
    fgets(input, sizeof(input), fppop);

    I'll give you a hint for the seg fault...

    Code:
    int i = -1;
    
    // If this fails to evaluate to true then... i won't be incremented
    if (strcmp(p, previousName) != 0) {
    i++;
    }
    //...
    strcpy(countries[i].countryName, p);
    ask yourself, Is i always an index in the bounds of my array?

  3. #3
    Registered User
    Join Date
    Apr 2007
    Posts
    7
    thanks for the reply zacs7,

    so from what i can grasp

    Code:
    sizeof(input)
    will automatically assign a max length for the input so i no longer have to define a constant like 1500?

    in regards to the segmentation fault, if i have initialised the variable previousName to be null on the first run thru, the value held at pointer p should always differ from it as it would have the first country name in the text file and therefore the value of i should be always be incremented as far as i can see

  4. #4
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    sizeof(input) will return the size of char input[1500] (in this case its 1 * 1500 = 1500 (where 1 is the size of a 'char').

    Add some debugging to your code, to find out where the segfault does occur. SegFaults (Access Violations) usually happen when you reference memory you have not yet allocated (memory you don't own). Also you should be initialising pointers otherwise they're "wild-pointers",

    Code:
    char * p = 0; // NULL
    hth.

  5. #5
    Registered User
    Join Date
    Apr 2007
    Posts
    7
    gotcha re the sizeof(input) thanks

    will work some debugging messages into various places of my code to try and ascertain exactly where the seg fault is happening.

    does this portion of code look legible tho as that is the part of the prog i was a bit unsure on

    Code:
    		p = strtok(NULL,","); // year string
    		dataYear = atoi(p);
    		countries[i].yearlyData[2006 - dataYear].year = atoi(p);
    		//p = strtok(NULL,","); //pop
    		//countries[i].yearlyData[2006 - dataYear].pop = atof(p);

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > while (!feof(fppop))
    > fgets(input, 1500, fppop);
    Is better written as
    while ( fgets(input, sizeof input, fppop) != NULL )

    > dataYear = atoi(p);
    Check that p isn't NULL before trying to use it.

    > countries[i].yearlyData[2006 - dataYear].year
    Check dataYear is in range before trying to use it.
    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.

  7. #7
    Registered User
    Join Date
    Apr 2007
    Posts
    7
    thanks chaps, did a bit of debugging last night and it appears the seg fault is happening earlier than i thought at this line

    Code:
    strcpy(countries[i].countryName, p);
    didnt have a lot of time to play about last night but im betting its a problem with the pointer p.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Try scattering some printf statements around to see what your variables actually contain before you try copying them places.


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

  9. #9
    Registered User
    Join Date
    Apr 2007
    Posts
    7
    cheers quzah, that was next on my hitlist - as p is a pointer to the start address of the array can i just reference it like

    Code:
    printf("Value of p:%s\n",p);

  10. #10
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    yes, &#37;s will try to read from a (char *)pointer to the next '\0'

  11. #11
    Registered User
    Join Date
    Apr 2007
    Posts
    7
    turned out there was a blank line at the end of my text file i was reading in....d'oh!!

    thanks for all ur help...i'll be back

  12. #12
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Just want to make sure this is not some typo here or if it is really your intent to store 12 years worth of data in an array that only can hold 11.
    Code:
    Data yearlyData[11]; // max. 12 year’s data (1995 – 2006)
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

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. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM