【学习 PG】为什么 PostgreSQL 中大量的初始化使用手动归零,而不是直接使用能够全部清零的 calloc

52 阅读1分钟
HI team,
I'm a newbie to the postgres.
When I learn the code of libpq, the achieve of PQmakeEmptyPGresult, cause my  curiosity.

The old version code:
 
PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
{
      PGresult   *result;

      result = (PGresult *) malloc(sizeof(PGresult));
      if (!result)
            return NULL;

      result->ntups = 0;
      result->numAttributes = 0;
      result->attDescs = NULL;
      result->tuples = NULL;
      result->tupArrSize = 0;
      result->numParameters = 0;
      result->paramDescs = NULL;
      result->resultStatus = status;
      result->cmdStatus[0] = '\0';
      result->binary = 0;
      result->events = NULL;
      result->nEvents = 0;
      result->errMsg = NULL;
      result->errFields = NULL;
      result->errQuery = NULL;
      result->null_field[0] = '\0';
      result->curBlock = NULL;
      result->curOffset = 0;
      result->spaceLeft = 0;
      result->memorySize = sizeof(PGresult);
      /*
            .............
      */
      return result;
}

My version:

PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
{
      PGresult   *result;

      result = (PGresult *) calloc(sizeof(PGresult));
      if (!result)
            return NULL;

      result->memorySize = sizeof(PGresult);
      /*
            .............
      */
      return result;
}

Why not have a change?I don't know.
I'm a newbie, so I don't think I can commit a patch for postgres, just instead of send mail to ask.

Yours,
Wenyi.

来自 Tom Lane 的回复

输入图片说明

换而言之,这样的手工初始化,并不比 calloc 降低多少效率,而且,它让维护变得容易:因为这样可以摆脱函数具体行为(Tome Lane 认为,依靠 calloc 把分配的内存先全部设置为0也是一种依赖函数特定行为的做法,这会让调试变得复杂)