SwiftCore
SwiftCore

Reputation: 659

Segmentation Fault on fopen

I'm getting an odd segmentation fault on the first line of my code.

All I do is call

FILE *src = fopen(argv[1], 'r');

And I get a seg fault with the message in gdb...

Program received signal SIGSEGV, Segmentation fault.

0x00007ffff779956d in _IO_file_fopen () from /lib/x86_64-linux-gnu/libc.so.6

I copy the name of the file directly into the run-time execution. Thoughts?

Upvotes: 0

Views: 3533

Answers (3)

Gevni
Gevni

Reputation: 43

instead of

FILE *src = fopen(argv[1], 'r');

you need to write

FILE *src = fopen(argv[1], "r");

Upvotes: 0

NPE
NPE

Reputation: 500883

The second argument to fopen() should be a string, not a char:

FILE *src = fopen(argv[1], "r");

Note the double quotes.

It is always a good idea to switch on compiler warnings and to keep an eye on them. My compiler picks up on the incorrect argument:

test.c:4:1: warning: passing argument 2 of 'fopen' makes pointer from integer without a cast [enabled by default]
In file included from test.c:1:0:
/usr/include/stdio.h:250:7: note: expected 'const char *' but argument is of type 'int'

Upvotes: 14

Mppl
Mppl

Reputation: 961

Probably the string passed is not null terminated, or you're acessing an invalid índex on argv

Upvotes: 0

Related Questions