sqlite源码中的一个潜在Bug

源码中在开始BTREE事务的时候,首先会调用btreeIntegrity(p)检测状态的正确性,其实现如下:

#define btreeIntegrity(p) \
  assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
  assert( p->pBt->nTransaction<=p->pBt->nRef ); \
  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  assert( p->pBt->inTransaction>=p->inTrans ); 

代码中调用如下:

int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  BtShared *pBt = p->pBt;
  int rc = SQLITE_OK;

  btreeIntegrity(p);

这样的调用不会出现任何问题,但如果假设是如下的调用方式呢?

if(false)
btreeIntegrity(p);
....

本来是想条件为假,不再检测状态正确性了,但结果还是检测了后面三个条件。这无疑会导致错误的发生。也许有人说加个括号不就好了吗?但我们在设计一个接口的时候是不应该考虑到使用者的使用方式的,也许有些初学者就是没有这些习惯呢。我们应该保证提供的接口哪怕最蹩脚的程序员也不会犯错误。

那么应该如何修改呢,修改的代码如下:

#define btreeIntegrity(p)  \
    do                     \
    {                      \
        assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef );  \
        assert( p->pBt->nTransaction<=p->pBt->nRef );                           \
        assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
        assert( p->pBt->inTransaction>=p->inTrans );                            \
}while(0)

这样btreeIntegrity就成为一个整体,不会引起上述的错误了。

http://www.cnblogs.com/chencheng/archive/2012/06/20/2557053.html

posted @ 2012-06-20 22:29  平凡之路  阅读(1915)  评论(4编辑  收藏  举报