所以我一直在自学 C,并且希望从一开始就学习如何正确管理内存并编写更好的代码,我一直在运行 Valgrind。这帮助我解决了内存泄漏问题,但我似乎无法摆脱这种“条件跳转或移动取决于未初始化的值/未初始化的值是由堆分配创建的”情况,尽管我已经缩小了范围到这段代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char* test = (char*) malloc(3);
strncpy(test, "123", 2);
printf("%s\n", test);
free(test);
return 0;
}
当我使用 ---track-origins=yes
运行 Valgrind 时,我得到了这个输出:
==91702== Conditional jump or move depends on uninitialised value(s)
==91702== at 0x100011507: strlen (mc_replace_strmem.c:282)
==91702== by 0x1000AA338: puts (in /usr/lib/libSystem.B.dylib)
==91702== by 0x100000EFA: main (valgrind_test.c:10)
==91702== Uninitialised value was created by a heap allocation
==91702== at 0x100010345: malloc (vg_replace_malloc.c:236)
==91702== by 0x100000EEA: main (valgrind_test.c:8)
这对我来说似乎是误报,但我对自己的知识没有足够的信心将其注销。也许我分配错误或使用 strncpy 错误?我不确定。
提前致谢
最佳答案
不,这是错误的代码。
你有一个包含 3 个未初始化字符的内存块。然后将 "12"
复制到其中,并且不要终止。当心 strncpy()
。
我引用 the documentation :
The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, the result will not be null-terminated.
由于源的前 2 个字符内没有终止,因此目标没有终止。
关于valgrind 对未初始化值的提示可能是误报吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346146/