gpt4 book ai didi

c - 夹板:来自 strcpy() 的新存储?

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:33 27 4
gpt4 key购买 nike

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

#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 而不是丢弃它(它消除了警告)是正确的解决方案吗?

最佳答案

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

if (strncpy(copy, str, len) == NULL)
return NULL;

关于c - 夹板:来自 strcpy() 的新存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19464573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com