0

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.

17
  • 1
    printf("%s\n", strerror(errno)); will tell you more.
    – mch
    Feb 23, 2015 at 13:55
  • 1
    You can you perror() in order to get you error message in stderr. Feb 23, 2015 at 13:56
  • 1
    @Jav, try using ssize_t for the headersize variable, and use the appropriate specifier "%ld", and see if the value is negative. Feb 23, 2015 at 14:07
  • 2
    to be even more correct you need to use (void*)header_p inside printf Feb 23, 2015 at 14:10
  • 3
    convert to unsigned long if you're stuck with a C89 compiler: printf("%p\t%lu\n", (void *) header_p, (unsigned long) headersize);. If you have a C99 compiler use "%zu" instead: printf("%p\t%zu\n", (void *) header_p, headersize);
    – pmg
    Feb 23, 2015 at 14:17

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.