如何用静态分析工具检测realloc导致的悬空指针问题?
检测第三方哈希表扩容引发的悬空指针问题
我使用的是一个C语言编写的第三方哈希表库,该库在哈希表需要扩容时,会通过realloc将键/值的内存空间翻倍。我清楚这一特性,但其他开发者并不了解,已经多次出现有人保存哈希表中值的引用供后续使用,进而触发悬空指针bug的情况。这类bug如果不熟悉该哈希表库及其潜在问题,调试起来难度极大,会耗费大量时间。
我想知道是否有可行的方法,通过Coverity等静态分析工具检测此类问题?我曾尝试使用-fsanitize=address -fsanitize=undefined编译程序,但并未检测出问题。
示例程序
#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; }
编译与运行情况
编译命令:gcc -o example example.c -Iinclude -g
使用gdb运行时,程序会在第28行崩溃,此时哈希表已扩容至大小4。
内容的提问来源于stack exchange,提问作者Brave
相关产品推荐
相关产品推荐

