llohse / libnpy

C++ library for reading and writing of numpy's .npy files
MIT License
361 stars 72 forks source link

[bug] Reading unsigned char as (signed) char #22

Closed dhbloo closed 2 years ago

dhbloo commented 2 years ago

In read_header(), header length is read as an unsigned, little-endian short int, which is currently done by reading two char and concatenating them into an unsigned int.

However the sign-ness of char in C++ is not specified (implementation defined). When char is treated as signed char, the code immediately overflows for byte in range [128, 255], and causing all latter buffer allocating go wrong.

  uint32_t header_length;
  if (version == version_t{1, 0}) {
    char header_len_le16[2];
    istream.read(header_len_le16, 2);
    header_length = (header_len_le16[0] << 0) | (header_len_le16[1] << 8); // header_length incorrect for signed char!
  .......
llohse commented 2 years ago

Thank you for reporting this. Indeed, there should to be a couple of reinterpret_cast<uint8_t>(). I'll fix this as soon as I can.

llohse commented 2 years ago

@dhbloo could you have a look at #23

dhbloo commented 2 years ago

It looks ok to me. I will close this issue.