I read/write data into a custom raw file where I used to write
version (int)
data
I implemented a more generic way to write my data and now the expected format is
headersize (size_t)
header (headersize)
data
Therefore, I manually added 4
(sizeof(int)
) to an old raw file (with ghex
) to make it compatible with the new implementation.
Now, my program is failing when malloc
-ing space for a header_p
on which I want to read the header
from the raw file.
size_t headersize;
fread(&headersize, sizeof(size_t), 1, fd);
printf("%p\t%d\n", header_p, (int) headersize);
header_p = malloc(headersize);
printf("%p\t%d\t%d\t%s\n", header_p, (int) headersize, errno,strerror(errno));
Returns
(nil) 4
(nil) 4 12 Cannot allocate memory
Why would malloc
fail on such operation? The headersize
seems correctly hard-written in the raw file since it's equal to 4
and errno
of 12
seems to indicate that I don't have enough memory but when I hard-code sizeof(int)
at the malloc
call, the failure doesn't occur anymore.
size_t headersize;
fread(&headersize, sizeof(size_t), 1, fd);
printf("%p\t%d\n", header_p, (int) headersize);
header_p = malloc(sizeof(int));
printf("%p\t%d\t%d\n", header_p, (int) headersize, errno);
Returns
(nil) 4
0x8e6e90 4 0
I suspect that the errno
of 12 hides something else but I don't understand what.