Reputation: 3167
FILE *inp = fopen(...);
int j, buff;
j = 40 - sizeof(int) - 4;
printf("%d\n", j);
fread(&buff, j, 1, inp);
printf("%d", j);
For some reason j is 32, then it jumps to some crazy high number in the second print. I'm fairly new to C but not to programming and can't figure this one out.
Upvotes: 0
Views: 506
Reputation: 19864
The prototype of fread is
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Where
size
This is the size in bytes of each element to be read.
In your case you are trying to read 32 bytes into 4 byte int which is undefined behavior.
If you have int buff[40];
The buff can hold 40 integer elements so the call can be like
fread(buff,sizeof(buff),1,inp);
Upvotes: 2
Reputation: 49189
Since almost assuredly buff
is a local array, it is stack allocated and fread is overwriting your stack including j since most likely 40 - sizeof(int) - 4
is greater than sizeof(buff)
.
Yeah - there's your problem. sizeof(buff) = sizeof(int)
, so assuming sizeof(int)
is 4, you're asking to read 40 bytes, which will overwrite 36 bytes past buff.
If you're trying to read an array of ints, you should declare an array of ints (and read no more than its size).
If you're trying to read 40 ints, you should do something like this:
int buff[40];
size_t amountRead = fread(buff, sizeof(int), 40);
or if it makes you happy.
int buff[40];
size_t size = sizeof(buff);
size_t amountRead = fread(buff, size, 1);
The latter is better in that the code will work independent of changes to the the dimension of buff.
And just to stave off future questions, it looks like you can read and write structs using fread
, and you can, but this is not a portable serialization strategy (mostly due to byte ordering, data type sizes and struct padding differences on differenct computers or compiler configurations).
It also looks like you can serialize arrays of integers with fread
, and you can, but it is also not portable because of data type size differences and byte ordering differences.
As long as you're on one computer, one compiler, one set of compiler settings, you're OK.
Upvotes: 1