6

I'm trying to write a word to a file using this function:

extern void write_int(FILE * out, int num) {
   fwrite(&num,sizeof(int),1, out);
   if(ferror(out)){
      perror(__func__);
      exit(EXIT_FAILURE);
   }
}

But I get a segmentation fault whenever it tries to run the fwrite. I looked at the man page for fwrite(3) and I feel like I used it correctly, is there something I'm missing?

user149100
  • 1,089
  • 3
  • 12
  • 16
  • What platform/compiler? Issues of alignment might matter. – abelenky Apr 23 '10 at 03:04
  • 2
    just make sure `out` is not `NULL`, rest is ok. – N 1.1 Apr 23 '10 at 03:14
  • when I tested this code, I wasn't thinking and decided to write to a test file called "test", which was also the name of the binary of my test program, which gave me a segfault. >.< So the function itself is fine, just make sure what you're passing into it is valid, as N 1.1 and others have suggested. – Paige Ruten Apr 23 '10 at 03:23
  • What platform/compiler? Issues of alignment might matter.
    Can you write anything else to the file successfully? I suspect your out-file may not be opened properly.
    – abelenky Apr 23 '10 at 03:06

3 Answers3

12

Try this instead:

void write_int(FILE * out, int num) {
   if (NULL==out) {
       fprintf(stderr, "I bet you saw THAT coming.\n");
       exit(EXIT_FAILURE);
   }
   fwrite(&num,sizeof(int),1, out);
   if(ferror(out)){
      perror(__func__);
      exit(EXIT_FAILURE);
   }
}

And why was your original function extern?

tylerl
  • 30,197
  • 13
  • 80
  • 113
  • 1
    Haha. Ok. Thanks. But now all it does is display "I bet you saw THAT coming." *self-facepalm* This isn't the first time it has happened nor will it be the last... The function was extern because I'm writing a library that I'll be using for a systems programming class next quarter... – user149100 Apr 23 '10 at 03:27
  • If your `FILE*` is `NULL`, that usually means either you forgot to open it, or your open failed. Check the man page for `fopen` (presumably that's what you're using). – tylerl Apr 26 '10 at 05:22
  • Is that platform independent? I am talking about endianity issues. – Tomáš Zato Jan 09 '17 at 19:45
0

Is the file handle valid? Did you fopen() with "w"? fwrite() will segfault if it's not.

The function itself really does nothing, so it's obviously the fwrite call that's the problem. Examine the arguments.

Paul Richter
  • 6,154
  • 2
  • 20
  • 22
0

out does not contain the address of the file, rather it contains the address of the file pointer your passing in main. This function prototype should be like:

extern void write_int(FILE * & out, int num);

In this way you are making a double pointer to the pointer in main which is then pointing to the file.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50