safe_strcmp and safe_strncmp assuming 8bit return value from strcmp and strncmp
Created by: shufps
Hi,
the bahaviour of this code is wrong - at least it was on my RISC-V code that is compiled with risc-v g++ 9.2.
The definition of strcmp states that both parameters are equal if the return value is 0 - but the return value is defined as integer and in my case, it tried to compare addressIndex
with auth
which gave 0x1100
back. But during the cast to int8_t
the upper 8bit get lost and the key is accepted as equal. This probably happens during 32bit-wise comparisons that would be totally fine if not only 8 of 32bits are used to determine the end-result.
Probably the same problem also is true for the strncmp variant.
inline int8_t safe_strcmp(const char* a, const char* b) {
if (a == b) return 0;
if (!a) return -1;
if (!b) return 1;
return static_cast<int8_t>(strcmp(a, b));
}
inline int8_t safe_strncmp(const char* a, const char* b, size_t n) {
if (a == b) return 0;
if (!a) return -1;
if (!b) return 1;
return static_cast<int8_t>(strncmp(a, b, n));
}