1

When I run the output program using gdb from the terminal it always ends with a segmentation fault at this function. But running this with eclipse debugger works fine.

ssize_t
read_from_file(char *arg, unsigned char *buf, size_t max_buf_len) {
  ssize_t result = 0;
  FILE *f = fopen(arg, "r");
  int c;
  while (!feof(f)) {
    size_t bytes_read;
    bytes_read = fread(buf, 1, max_buf_len, f);
    if (ferror(f)) {
      result = -1;
      break;
    }

    buf += bytes_read;
    result += bytes_read;
    max_buf_len -= bytes_read;
  }

  fclose(f);
  return result;
}

Error message from gdb

[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
_IO_feof (fp=0x0) at feof.c:35
35      feof.c: No such file or directory.

I tried using alternatives to feof() Like

while((c = fgetc(file)) != EOF)

But I get the same results

[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
_IO_getc (fp=0x0) at getc.c:37
37      getc.c: No such file or directory.

Does anyone know where this error is originating from?

Jens
  • 69,818
  • 15
  • 125
  • 179
yrekik
  • 55
  • 1
  • 6

2 Answers2

3

Note that while (!feof(f)) is always a bug because in C the end-of-file condition is only detected after an attempt to read, never before.

And then, you violated two of the ten commandments (2 and 6), by not checking the return value from fopen, which can be NULL and cause segmentation faults when you use the file pointer.

Yes, no matter what you tell us about your IDE and debugging, you got a NULL pointer from fopen() and passed it to feof(), which is literally in the error message you got and the question title: fp=0x0.

Jens
  • 69,818
  • 15
  • 125
  • 179
1

You should check fopen return value.

  • I know this is strange part because I have the same args on eclipse debugger and the fopen function returns the correct pointer to the file when I step through the code – yrekik Apr 19 '17 at 11:58
  • @yrekik I would bet you pass a relative file path and not a full absolute path. In that case it depends on your working directory which might be different in your debugger and your command line. – Gerhardh Sep 21 '18 at 14:19