I need to write data to a binary file using C\'s I/O functions. The following code causes a runtime exception :
#include \"stdio.h\"
int main(int argc,char
Apparently, I'm, trying to access data at 0x0000004 or something like that.
int val = 4
There's the issue. fwrite
is designed to work with strings, and as such its first input is a pointer, the location of a string in memory. You are passing the value of val
directly (4) rather than the address of val
to fwrite
; however, the memory at 0x00000004 is not valid program memory and thus an error is given.
To fix this, change this:
fwrite((const void*)val,sizeof(int),1,fp);
Into this:
fwrite((const void*)&val, sizeof(int), 1, fp);
The "&" operator indicates the location of val
. This would be a valid address in memory.