我正在使用redis的sds库并在其上运行scan-build。然后我得到两个错误,非常相似。我将在这里提出一个错误。
sds.c:92:22: warning: Out of bound memory access (accessed memory precedes memory block)
sh->buf[initlen] = '\0';
有问题的功能是:
/* Create a new sds string with the content specified by the 'init' pointer
* and 'initlen'.
* If NULL is used for 'init' the string is initialized with zero bytes.
*
* The string is always null-termined (all the sds strings are, always) so
* even if you create an sds string with:
*
* mystring = sdsnewlen("abc",3");
*
* You can print the string with printf() as there is an implicit \0 at the
* end of the string. However the string is binary safe and can contain
* \0 characters in the middle, as the length is stored in the sds header. */
sds sdsnewlen(const void *init, size_t initlen) {
struct sdshdr *sh;
if (init) {
sh = malloc(sizeof *sh+initlen+1);
} else {
sh = calloc(sizeof *sh+initlen+1,1);
}
if (sh == NULL) return NULL;
sh->len = initlen;
sh->free = 0;
if (initlen && init)
memcpy(sh->buf, init, initlen);
sh->buf[initlen] = '\0';
return (char*)sh->buf;
}
我真的不明白这个错误,我很确定这里没有错误,因为它是sds库的一个非常基础的部分,如果有错误的话,它本已在生产中显示出来。
我该如何解决这个问题?通过显式告诉cland-analyzer,这不是一个错误,或者通过更改代码使clang-analyzer感到高兴。