views:

205

answers:

3

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?

A: 

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
HINT: fwrite takes void * and casts it to char* so align = not a problem
Joshua
+2  A: 

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
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...
lol at the effects of psychic debugging
Joshua
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
A: 

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