[英]modulo size_t yields “The result of expression ' ' is undefined”
在 64 位系統上,當使用模運算符和 size_t 類型時,我從 clang 分析器收到以下警告:
htable.c:38:62: warning: The result of the ' ' expression is undefined [clang-analyzer-core.UndefinedBinaryOperatorResult]
return ht->num_buckets > 0 ? (ht->hash_fn(key, ht->seed) % ht->num_buckets)
^
hash function的結果有size_t,桶數也是size_t。 最終這轉化為無符號長。 AFAIK 結果不能為負,我檢查了桶數是否為零。
hash function 可能會溢出,但由於它用於鏈接 hash 表,這不會導致問題(如果我沒記錯的話)。
這里有什么問題? 這是誤報嗎?
出現警告的function:
static size_t
htable_bucket_idx(htable_t* ht, void* key)
{
if (!ht || !key) {
printf("htable - bucket_idx: Invalid Argument!\n");
exit(-1);
}
return ht->num_buckets > 0 ? (ht->hash_fn(key, ht->seed) % ht->num_buckets)
: ht->hash_fn(key, ht->seed);
}
hash function是FNV的粗略簡化版本
size_t
fnv_hash_ul(const void* in, unsigned int seed)
{
size_t h = seed;
const unsigned int prime = 0xFDCFB7;
unsigned long ul = *((unsigned long*) in);
return (h ^ ul) * prime;
}
htable_t
的定義(為簡潔起見省略了其他類型,根據要求附加)
typedef size_t (*htable_hash)(const void* in, unsigned int seed);
typedef struct htable
{
htable_hash hash_fn;
htable_keq keq;
htable_cbs_t cbs;
htable_bucket_t* buckets;
size_t num_buckets;
size_t num_used;
unsigned int seed;
} htable_t;
function的調用:
static int
htable_add_to_bucket(htable_t* ht, void* key, void* value, bool rehash)
{
if (!ht || !key) {
printf("htable - add_to_bucket: Invalid Argument!\n");
exit(-1);
}
size_t idx = htable_bucket_idx(ht, key);
[...]
編譯器信息:
clang version 11.1.0
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-pc-linux-gnu/10.2.0
Candidate multilib: .;@m64
實際上,這似乎是一個誤報。 我可以通過將 htable_rehash() 從以下位置更改來消除所有警告:
static int htable_rehash(htable_t* ht)
{
...
ht->num_buckets <<= 1UL;
...
}
至
static int htable_rehash(htable_t* ht)
{
...
ht->num_buckets *= 2;
...
}
詭異的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.