0

I'm having trouble figuring out why my code is having a seg fault while reading code from a file in c. I've attached the code and valgrind output below. Thanks for any help!

FILE *fp;
fp = fopen("filename", "r");
char line[100];
while (fgets(line, 100, fp) != NULL) {
==4545== Invalid read of size 4
==4545==    at 0x4E9E34B: fgets (iofgets.c:50)
==4545==    by 0x401289: main (game.c:180)
==4545==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==4545==
==4545==
==4545== Process terminating with default action of signal 11 (SIGSEGV)
==4545==  Access not within mapped region at address 0x0
==4545==    at 0x4E9E34B: fgets (iofgets.c:50)
==4545==    by 0x401289: main (game.c:180)
  • 7
    You did not check if `fp` is `NULL`. – mch Aug 16 '17 at 07:49
  • @alinsoar: found a better one, a duplicate should have the problem of not checking a pointer returned by a library call... –  Aug 16 '17 at 08:09

1 Answers1

4

This line

==4545==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

tells you you're dereferencing a NULL pointer (Address 0x0 ...)!

With the code you show, this can only mean fopen failed and returned 0/NULL. Always check the return values of your function calls.

  • 3
    [The Ten Commandments for C Programmers](http://skull.piratehaven.org/~bapper/298c/ten-commandments.html), items 2 and 6. ;-) – DevSolar Aug 16 '17 at 07:51
  • haha, nice document :) –  Aug 16 '17 at 07:52
  • 1
    It's positively ancient (I've seen this in the 80's...), but most items are still surprisingly topical. ;-) – DevSolar Aug 16 '17 at 07:54
  • @DevSolar well, I don't necessarily agree with item 3 there. Often good, but imagine you're dealing with pointer types: either the cast is unnecessary (and all is fine) or you're accessing an object through a wrong type (UB) and a cast would just silence the compiler about it... –  Aug 16 '17 at 07:58
  • Items 4 and 9 are artifacts of a bygone era as well, but an interesting glimpse of the past. The rest is pure gold to this day. ;-) – DevSolar Aug 16 '17 at 08:03
  • So does that mean that the file I'm trying to open doesn't exist? – DuKangaroo Aug 16 '17 at 08:09
  • @DuKangaroo no, it means opening it fails. The file not existing is **one** possible reason, others include wrong permissions etc. –  Aug 16 '17 at 08:10
  • Thank you so much!! I've managed to get that part working now. – DuKangaroo Aug 16 '17 at 08:21