Reputation: 337
I use some external lib written in C that implement hash table. When hash table size need to grow it uses realloc to double the memory space for keys/values.
I familiar with this behavior but others don't and it happen more than once that someone saved reference to value in the hash table to use later and that led to dangling pointer bug.
This bug is hard to debug if you are not familiar with this hash table lib and this potential problem and you can waste a lot of time to debug it.
I've wonder if there is some good why to detect such issue using static analysis tools like Coverity or static analyzers?
I've tried to use -fsanitize=address -fsanitize=undefined
but it didn't complain.
Example program:
#include <stdio.h>
#include "khash.h"
typedef struct {
int data[20000];
} array_val;
KHASH_MAP_INIT_INT(example_hash, array_val)
khash_t(example_hash) hash;
int main() {
array_val *ref;
int ret;
khiter_t iter;
kh_init_inplace(example_hash, &hash);
kh_put(example_hash, &hash, 1, &ret);
iter = kh_get(example_hash, &hash, 1);
ref = &kh_val(&hash, iter);
ref->data[0] = 0;
kh_put(example_hash, &hash, 2, &ret);
kh_put(example_hash, &hash, 3, &ret);
kh_put(example_hash, &hash, 4, &ret);
ref->data[0] = 0;
return 0;
}
Compile with: gcc -o example example.c -Iinclude -g Run with gdb you will notice program crashes in line 28, after table size grow (size 4).
Upvotes: 1
Views: 42