I'm using the sds library from redis and run scan-build on it. Then I get two errors, that are very similair. I'll present one of the errors here.
sds.c:92:22: warning: Out of bound memory access (accessed memory precedes memory block)
sh->buf[initlen] = '\0';
The function in question is:
/* 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;
}
I really don't understand this error and I'm pretty sure there isn't an error here since it's a quite fundamental part of the sds library that should have shown itself in production already if there was a bug.
How can I fix this? Either by explicit tell cland-analyzer that this is not a bug or by changing the code to make clang-analyzer happy.