[英]memory error using valgrind, strcpy
我一直在使用valgrind,但由于某种原因,我使用一个简单的字符串副本,在C中使用两个大小相同的字符串来获取内存错误。
该守则的影响是:
node->entry = (char*)malloc(strlen(string)*sizeof(char));
strcpy(node->entry, string);
字符串为: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)
谢谢您的帮助!
malloc(strlen(string)*sizeof(char));
你没有考虑结尾'\\0'
。 所以应该是(strlen(string) + 1)
。
边注:
type *x;
x = malloc(size * sizeof(*x))
比...更可维护
type *x;
x = (type *)malloc(size * sizeof(type));
因为你不重复自己3次。
你的代码坏了:
strcpy()
写入未分配的内存并导致缓冲区溢出错误。 malloc()
的返回值。 此外,请注意sizeof (char)
始终为1,因此不需要涉及它。 只需使用:
node->entry = malloc(strlen(string) + 1);
或者,检查是否有strdup()
因为它结合了以上所有内容。
在一般情况下,正如@Shahbaz指出的那样,最好在取消引用左手指针的结果上使用sizeof
运算符,以避免重复类型名称:
type *x;
x = malloc(amount * sizeof *x);
另外,请注意sizeof
不是函数,只有在参数是类型名称时才需要括号,并且正如我刚才所说的那样,应该避免使用括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.