使用valgrind,strcpy发生内存错误

Cai*_*tri 3 c malloc valgrind strcpy

我一直在使用valgrind,但是由于某种原因,我在C中使用带有两个相同大小的字符串的简单字符串副本,不断遇到内存错误。

生效的代码是:

node->entry = (char*)malloc(strlen(string)*sizeof(char));
strcpy(node->entry, string);
Run Code Online (Sandbox Code Playgroud)

字符串为:char * string =“ Hello There”。错误是:大小为2的无效写入

==2035==    at 0xD494: memmove$VARIANT$sse42 (mc_replace_strmem.c:987)
==2035==    by 0x100001793: __inline_strcpy_chk (_string.h:94)
==2035==    by 0x100001699: createList (main.c:10)
==2035==    by 0x100001BE6: main (main.c:132)
==2035==  Address 0x10000c0fa is 10 bytes inside a block of size 11 alloc'd
==2035==    at 0xB823: malloc (vg_replace_malloc.c:266)
==2035==    by 0x100001635: createList (main.c:9)
==2035==    by 0x100001BE6: main (main.c:132)
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

Sha*_*baz 5

malloc(strlen(string)*sizeof(char));
Run Code Online (Sandbox Code Playgroud)

您没有考虑到结局'\0'。因此应该如此(strlen(string) + 1)


边注:

type *x;
x = malloc(size * sizeof(*x))
Run Code Online (Sandbox Code Playgroud)

type *x;
x = (type *)malloc(size * sizeof(type));
Run Code Online (Sandbox Code Playgroud)

因为您不会重复3次。