Thread: Simple Structure yet Segmentation Fault! please help

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    4

    Unhappy Simple Structure yet Segmentation Fault! please help

    Yeah so I have coded this really simple program using one structure, with the information being scaned in to the structure from a seperate file called poeple.dat.

    Within my master while loop im printing the character array g1.names[i]. For some reason I cant figure out, I am getting a segmentation fault after exiting the master while loop. All information is scaned in successfully yet the program always ends in a segmentation fault.

    My code is this
    Code:
    #include <stdio.h>
    #define FILENAME "poeple.dat"
    
    struct building
    {
            char names[100];
            int var1, var2, var3, var4;
    };
    
    int main(void)
    {
            struct building g1;
            FILE *people;
            int i=0;
            char letter;
    
            people = fopen(FILENAME, "r");
    
            while((letter=fgetc(people))!=EOF)
            {
                    g1.names[i]=letter;
                    i++;
                    while(letter!='\t')
                    {
                            letter=fgetc(people);
                            g1.names[i]=letter;
                            i++;
                    }
                    g1.names[i]=0;
    
                    fscanf(students,"%i%i%i%i",&g1.var1, &g1.var2, &g1.var3, &g1.var4);
    
                    i=0;
    
                    printf("%s",g1.names);
            }
    
    
            fclose(people);
            return(0);
    }

    my output always looks like this

    Code:
    Erezah
    Erez
    Kriehn
    Bel
    Bzammm
    Tester
    Testah  Segmentation fault
    Ive rebuilt this code many times and completely analysed this code but cant figure out for the life of me whats wrong.

    any help would bo much appreciated, thanks.

  2. #2
    Registered User
    Join Date
    Dec 2004
    Posts
    3
    good question, I hope someone can help you because I dont see anything wrong, but then again I suck at C programming.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well one thing you'll find is that a char can NEVER store EOF. As such, you need to change that into an int.

    Also, you shouldn't rely on finding a '\t' as a size limit on your array. You could easily read a corrupt data file and have it run off the end of your buffer, because it never actually finds a tab.

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

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    4
    Hey thanks for the tip, I didnt know that a variable decteting an EOF had to be an Integer.

    Ok, i modified my while loop to use a different variable to detect the the EOF, Yet now it scans in the first name and gives me yet another segmentation fault. What exactly causes a segmentation fault?

    Instead of using '\t' could i use a NULL to stop scaning to that character array? if the input looks like:
    Code:
    Name    93    29    90
    My while loop now looks like this
    Code:
           while((end=fgetc(people))!=EOF)
            {
                    letter=fgetc(people);
                    i++;
    
                    while(letter!=NULL)
                    {
                            letter=fgetc(people);
                            g1.names[i]=letter;
                            i++;
    //                      printf("%c",letter);
                    }
                    g1.names[i]=0;
    
                    fscanf(people,"%i%i%i%i",&g1.HW, &g1.Final, &g1.Test1, &g1.Test2);
    
                    i=0;
    
                    printf("%s",g1.names);
            }
    thanks

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well, null won't be stored in a text file. So that's a bad idea to use it. What I meant earlier as control of your array size, is that, you need to keep track of where you are in the array in comparison to you reaching the end of it. Otherwise, you'll just merrily march off the end, which is what's happening to you.

    There are a few ways to do this:

    1) Read a name until you run into a white space character. (isspace() will do the trick) This would assume that the "name" portion is only ever one word
    2) Read a name until you run into a number. (isdigit() will do the trick) This would assume that there are never numbers in the name itself.

    However, there is an easier way to do both of these things. You could always use something like fscanf to read the line into the needed variables. Something like:
    Code:
    fscanf( "%s %d %d %d %d", g.name, &g.v1, &g.v2, &g.v3, &g.v4 );
    If you use this method, you will want to check the return value of fscanf, to make sure it matches up with the total number of items you're scanning in. If it doesn't match up, then the scan didn't work correctly and some form of error has occurred.

    You could also use something like fgets to read the entire line into a buffer, and then use something like sscanf to parse it properly.

    At any rate, one thing you need to do is keep track of where you are in your buffer as you're going along. What is happening is:
    Code:
    struct building
    {
            char names[100];
            int var1, var2, var3, var4;
    };
    Somewhere along the line, you're running past the 100 characters of space you've set aside for names. And as such, it gives you a segmentation fault, because you're running out of bounds.

    Were we to read one character at a time until the character was, for example, 'x', or until we reach the end of our allowed space, we could do something like:
    Code:
    struct building b;
    int n = 0, c;
    while( (c = fgetc( file )) != 'x' && n < 100 )
    {
        b.names[n] = c;
        n++;
    }
    This would:
    1) Read a c haracter from file, and store it in c.
    2) Check c to see if it is 'x':
    -- if so, it doesn't enter the body of the loop, and stops looping
    3) Checks the variable n to see if we're over our limit.
    -- if so, it doesn't enter the body of the loop, and stops looping
    4) Assigns the value stored in c to the current slot in the array.
    5) Increments the count of n to represent the fact that we have stored one more character.

    Now this is slightly incorrect, because if g.names is to be treated as a string, I should be stopping at "n < 99" so there is room for the null character, which by definition makes a string a string. But I'll leave that adjustment, as well as the adding of the null, as an exercise to the reader, as they say.

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

  6. #6
    Registered User
    Join Date
    Dec 2004
    Posts
    4
    Cool that helped alot more. Ive decided that instead of limiting myself to [100] ive added lines to realloc information inside my while loop so that every time i scan a letter it will realloc space for g1.names[].

    Its working out pretty well but im getting one error in my structure.

    Code:
    struct building
    {
            int var1, var2, var3, var4;
            char names[];
    };
    the error is this:
    Code:
    test.c: In function `main':
    test.c:27: invalid use of flexible array member
    Did I write char names[]; wrong? If i put in a variable like (char names[a]) I get an error saying undifined variable in structure.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You'll need a character pointer instead of an array.
    Code:
    struct building
    {
            int var1, var2, var3, var4;
            char *names;
    };
    Be sure and call free when you're done with the memory you've allocated.

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

  8. #8
    Registered User
    Join Date
    Dec 2004
    Posts
    4
    Thanks man, youve really helped me alot. I appreciate it.

    -program done

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with segmentation fault please!
    By JRusty15 in forum C Programming
    Replies: 2
    Last Post: 11-04-2008, 09:38 AM
  2. Why am I getting segmentation fault on this?
    By arya6000 in forum C++ Programming
    Replies: 6
    Last Post: 10-12-2008, 06:32 AM
  3. segmentation fault... first time with unix...
    By theMethod in forum C Programming
    Replies: 16
    Last Post: 09-30-2008, 02:01 AM
  4. fopen segmentation fault
    By fguy817817 in forum C Programming
    Replies: 27
    Last Post: 06-04-2008, 12:17 PM
  5. simple server & client getting Segmentation fault error
    By blondieoubre in forum Linux Programming
    Replies: 2
    Last Post: 12-11-2007, 06:26 AM