一个悬垂指针的bug

我们产品的code 用了sqlite的源码:

// lang/sql/sqlite/src/hash.h, lang/sql/sqlite/src/hash.c:

    struct HashElem {
      ...
      const char *pKey;

    void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
      ...
      new_elem->pKey = pKey;  // the pKey pointed to a mem provided by the caller
      new_elem->data = data;

    static HashElem *findElementWithHash(
        ...
        if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
          return elem;

上面的代码表示, HashElem->pKey 的内存 由调用方提供. 所以调用方需要保证 hash entry的 pKey 指向有效内存.而我们的代码里 有这个bug:

    typedef struct {
        char key[N]; // 给 HashElem->pKey的内存
        ...
    } ABC;

    static int cleanup()
       ...
       if (remove)
           sqlite3HashInsert(cache, abc->key, NULL); // remove entry from hash table.
       sqlite3_free(abc);

大致是这样. 在remove为false的情况下, 此hash entry不会从 hash table中移除. 但是相应的key 内存已经free了. 所以hash table里有悬垂指针.

说起来很简单, fix也简单, 应该一行改动就够了. 但是内存问题都是 随机出现, 定位起来太费劲了.

posted @ 2016-02-25 13:21  brayden  阅读(250)  评论(0编辑  收藏  举报