Shen
Shen

Reputation: 3169

fclose() seg fault

Why will this simple function cause seg fault?

int main(int argc, char** argv) {
    FILE* file1;
    file1 = fopen(argv[argc + 1], "wt");
    fclose(file1);
}

Upvotes: 0

Views: 409

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

Your fopen() is failing to open the file, so fp is NULL, so fclose() is legitimately objecting by crashing. Check the return from fopen().

Also, by definition, argv[argc] == 0 and argv[argc+1] is beyond the end of the array. In practice, on Unix systems, it will often be the name=value of the first environment variable, but it is unlikely to be a valid filename and most certainly wasn't obtained legitimately.

If your program is invoked as:

./a.out file.txt

then the file name is argv[1]; the string pointed at by argv[0] is the name of the program, a.out give or take path information, and argc == 2 and argv[2] == 0. Don't forget to check that argc == 2 before trying to open the file.

Always check return statuses, especially from 'known to fail' function such as fopen(). And print the name that you're opening - it would have told you a lot about your problem - after checking that argc is set to a value you expect.

Upvotes: 3

ckruse
ckruse

Reputation: 9740

You access two elements after the last element of argv. You also don't check the return value of fopen(), both could cause the segfault.

Upvotes: 2

Related Questions