我是C的新手,我正在和Valgrind一起练习。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
int ints[10];
char myString[50];
for (i=0; i<=10; i++) {
ints[i] = rand() % 10;
}
printf("''string'' is %lu characters long\n", strlen(myString));
strcpy(myString, "This is a medium sized string");
printf("''string'' is %lu characters long\n", strlen(myString));
return 0;
}
我的Valgrind输出:
==5425== Syscall param write(buf) points to uninitialised byte(s)
==5425== at 0x260E9A: write$NOCANCEL (in /usr/lib/system/libsystem_kernel.dylib)
==5425== by 0x17E5E8: __sflush (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x180CAA: __sfvwrite (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x18B191: __vfprintf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x1AF2DA: __v2printf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x1AF6AF: __xvprintf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x186B29: vfprintf_l (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x18496F: printf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x100000E73: main (test.c:15)
==5425== Address 0x10001236e is 14 bytes inside a block of size 4,096 alloc'd
==5425== at 0x6DEB: malloc (in /usr/local/Cellar/valgrind/3.9.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==5425== by 0x181855: __smakebuf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x196217: __swsetup (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x1AF158: __v2printf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x1AF6AF: __xvprintf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x186B29: vfprintf_l (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x18496F: printf (in /usr/lib/system/libsystem_c.dylib)
==5425== by 0x100000E73: main (test.c:15)
==5425== Uninitialised value was created by a stack allocation
==5425== at 0x100000DF0: main (test.c:6)
我认为错误是由于当我进行第一次myString
调用时printf
为“空”这一事实,但是,我不确定如何解决它。< / p>
谢谢!
答案 0 :(得分:1)
在此处调用myString
时,字符strlen
未初始化:
printf("''string'' is %lu characters long\n", strlen(myString));
当strlen
函数通过myString
搜索'\0'
时,它会读取未初始化的数据。这就是在valgrind中触发错误的原因。
要解决此问题,请添加初始化:
char myString[50] = {0};
答案 1 :(得分:0)
我认为错误是由于myString是&#34;空&#34;
不是真的。 myString
不是空的,它未初始化,其内容未定义,因此使用strlen(myString)
是非法的。
您可以将其初始化为空字符串,如下所示:
char myString[50] = "";
答案 2 :(得分:0)
说myString
为空,它有一些内容是不正确的。只是内容是任意的。
这意味着它可能不在那里的某个地方有一个零字节来终止字符串,所以在它上面调用printf
或strlen
是而不是一个好主意,因为它可能会在缓冲区的末尾运行并导致问题。
您可以通过确保它是一个有效的字符串来使其工作,例如:
*myString = '\0';