From c697170db00a0ad56760688fa9d0bae9c1773d0b Mon Sep 17 00:00:00 2001 From: Thomas Peters Date: Mon, 8 Aug 2022 15:26:02 -0400 Subject: [PATCH] cnpy.h::npy_save: fix bug when nels = 0 and data = NULL When nels = 0, no bytes from `const T* data` are written to the npy file (line 219: fwrite(data,sizeof(T),nels,fp)). Therefore, the crc of the to-be-written data only needs to be computed for the numpy header, as done on line 171. It might be thought that `crc32(initial_crc, data_ptr, data_size)` would always return `initial_crc` if `data_size = 0`. This is true for every value of data_ptr *except* NULL. In this case crc32 returns 0, *independent* of initial_crc. The result of calling npz_save with a shape of total size 0 (i.e., the product of all elements in the shape) should not depend on whether `data` is a null pointer or not. Fix this bug by only updating the crc when nels != 0, independent of the value of `data`. --- cnpy.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cnpy.h b/cnpy.h index 0d3bb4c..8f894e8 100644 --- a/cnpy.h +++ b/cnpy.h @@ -169,7 +169,9 @@ namespace cnpy { //get the CRC of the data to be added uint32_t crc = crc32(0L,(uint8_t*)&npy_header[0],npy_header.size()); - crc = crc32(crc,(uint8_t*)data,nels*sizeof(T)); + + if (nels) + crc = crc32(crc,(uint8_t*)data,nels*sizeof(T)); //build the local header std::vector local_header;