samedi 14 mai 2016

fread segmentation fault on local variable

With the following program I get a segmentation fault when calling fread:

static FILE *randomFile = (FILE*)0;
static void myFunction() {
  unsigned char rand;
  unsigned int i;
  [...]
  for (i = 0; i < 1000; i++) {
    //LINE 88 BELOW
    fread(&rand, sizeof(unsigned char), 1, randomFile);
    printf("all well?: %hu\n", (unsigned short) rand);
    [...]
  }
  [...]
}
int main() {
  int i;
  randomFile = fopen("/dev/urandom", "rb");
  if (randomFile == 0) {
    return EXIT_FAILURE;
  }
  [...]
  for (i = 0; i < 1000; i++) {
    myFunction();
    [...]
  }
  [...]
  fclose(randomFile);
  return EXIT_SUCCESS;
}

below is the output of gdb's run and backtrace commands

$ gdb a.out
[...]
(gdb) run
[...]
all well?: 5
all well?: 234
all well?: 9
all well?: 79
all well?: 26
all well?: 108
all well?: 21
all well?: 195
all well?: 192
all well?: 148
all well?: 64
all well?: 211
all well?: 245
all well?: 90
all well?: 173
all well?: 238
all well?: 167
all well?: 125
all well?: 14

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
(gdb) bt
#0  0x00007ffff7a9ec82 in free () from /lib64/libc.so.6
#1  0x00007ffff7a96856 in __underflow () from /lib64/libc.so.6
#2  0x00007ffff7a945a8 in __GI__IO_file_xsgetn () from /lib64/libc.so.6
#3  0x00007ffff7a898e6 in fread () from /lib64/libc.so.6
#4  0x0000000000400b69 in myFunction ()
    at FileName.c:88
#5  0x0000000000400ebc in main (argc=1, argv=0x7fffffffdfd8)
    at FileName.c:173

I don't see how I could be using the pointers wrong... It's a local variable on the stack which is guranteed to be a valid location with a fixed size... Especially since it works several times before eventually failing. What am I missing?




Aucun commentaire:

Enregistrer un commentaire