1

我正在努力学习和更好地理解夹板,我想知道我从这段代码中得到的一个错误:

#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/*@null@*/ /*@only@*/ char *dupStr(const char *str) {
    char *copy;
    size_t len;

    len = strlen(str) + 1U;
    if (!(copy = malloc(len * sizeof *str))) {
        return NULL;
    }
    (void) strncpy(copy, str, len);
    return copy;
}

错误是:

Splint 3.1.2 --- 26 Feb 2013

test.c: (in function dupStr)
test.c:13:9: New fresh storage copy (type void) cast to void (not released):
                (void)strncpy(copy, str, len)
  A memory leak has been detected. Storage allocated locally is not released
  before the last reference to it is lost. (Use -mustfreefresh to inhibit
  warning)

Finished checking --- 1 code warning

将返回值分配给copy而不是丢弃它是正确的解决方案(它摆脱了警告)?

4

1 回答 1

0

您不想忽略 的返回值strncpy,这就是splint抱怨的原因。你想要这样的东西:

if (strncpy(copy, str, len) == NULL)
    return NULL;
于 2014-01-26T15:49:52.437 回答