Problem writing int to binary file in C

前端 未结 6 2075
一整个雨季
一整个雨季 2021-01-06 21:11

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         


        
6条回答
  •  鱼传尺愫
    2021-01-06 22:10

    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.

提交回复
热议问题