c中的内存泄漏错误

memory leak Error in c

我有这个代码

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",包括字符串终止符。您在这里没有使用任何字符串函数,但也许还有其他代码可以使用。请展示完整的可验证示例。

您没有 post 整个代码,但现在评论了 "When I print the string..."(并在我输入时编辑了问题)。

大小必须是11。你也需要复制终止符。

chars = realloc (chars, 11);
memcpy(chars, hey, 11);