Hello, I'm getting a segmentation fault in my code, at the IF statement. Can anyone tell me why? The printf() statement right before outputs the correct data, so *buffer definitely isn't null. Thanks for your help.

int main(int argc, char *argv[])
        FILE *inputFile, *rejects;
        char hold[200], hold2[30], *buffer = &hold[0], *buffer2;
        int x = 0, numStudents = 0;
        struct Student students[100], currentStudent;

        /* opens the file */
        inputFile = fopen(argv[1], "rt");
        printf("\nFile %s opened...\n", argv[1]);

        /* while there are still lines of input, read the next line */
        while(fgets(hold, 150, inputFile))
                printf("In the while loop...\n");
                printf("input: %s", hold);
                printf("*buffer: %c\nx: %d\n", *buffer, x);
                /* seg. fault at this "if" statement */
                if(*buffer == '|')

Recommended Answers

All 5 Replies

Try setting

hold[0] = '\0';

Or you may try using buffer[0] == '|'

What's the rest of the code?

Without a complete example, and your input file, it's hard to figure out what you're doing wrong at the moment.

hold[0] = '\0' worked! Why in the world would that make a difference to buffer? Shouldn't fgets() fill the remainder of hold with null bytes until the end of the string is reached???

Your fix makes no sense at all.

> struct Student students[100], currentStudent;
Writing more than 100 students however would be a disaster.

Like I said, the WHOLE CODE if you want a real answer, not some "voodoo" fix that masks the immediate issue.

Try setting

hold[0] = '\0';

Or you may try using buffer[0] == '|'

buffer[0] means *(buffer + 0) which can be simplified as *(buffer)
This is obviously same as *buffer

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.