简体   繁体   中英

Malloc fails with errno 12

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.

There is your problem. sizeof(size_t) must take the pointer size, and may/may not be sizeof(int) . If you print it with the (int) cast, it looks okay, because only the least significant 4 bytes (in your case) are evaluated. If you use it for malloc() then the whole size(size_t) is used, and it's either garbage or part of your header.

When you're pickling numbers, you should:

  • Worry about endianness, and convert it to either little/big endian (or leverage hton* from arpa/inet.h )
  • Use specific-width integers from stdint.h , never ever pickle a type without specified width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM