1

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:

hash table lib

#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).

3
  • Static analysis is the best way to find bugs, of course. But if you fail to find a tool that detects your type of error: First idea: How about wrapping the external library in your own interface of C functions that protects the user from working with raw pointers? Second idea: use dynamic analysis (i.e. valgrind) to find the bugs.
    – Matthias
    yesterday
  • I've added example code. If problem is not reproduced try to increase size of data array. Static analysis tools will detect it in compile time?
    – Brave
    yesterday
  • compile with -fsanitize=address detects it at runtime
    – Brave
    yesterday

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.