我有这个代码
char* chars = (char*) malloc (sizeof(char));
memcpy(chars, "", 0);
char* hey = "hello doit";
chars = (char*) realloc (chars, 10);
memcpy(chars, hey, 10);
printf("string: %s\n", chars);
free(chars);
我的内存出现错误
Address "xxxxxxx" is 0 bytes after a block of size 10 alloc'd
我做错了什么?
最佳答案
10 个字节不足以包含 "hello doit"
(包括字符串终止符)。您在这里没有使用任何字符串函数,但也许还有其他代码可以使用。请展示完整的可验证示例。
您没有发布整个代码,但现在评论了“当我打印字符串时...”(并在我输入时编辑了问题)。
大小需要为 11。您还需要复制终止符。
chars = realloc (chars, 11);
memcpy(chars, hey, 11);
关于c - c中的内存泄漏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026944/