char * 后无法释放内存

Can't free memory after char *

我在程序结束时尝试释放内存时遇到问题。它总是坏掉。你能告诉我问题出在哪里吗?

int main() {

char* word = NULL;
int i = 0;
char str1[12] = "oko";

while (str1[i]) {
    str1[i] = tolower(str1[i]);
    i++;
}

printf("%s", str1);

word = (char *)malloc(strlen(str1) + 1);
word = str1;
printf("%s", word);

free(word);
system("pause");

return 0;
}

在你的代码中,通过说

word = str1;
  1. 你正在覆盖 malloc()-ed 指针
  2. 造成内存泄漏。

稍后,通过在 word 上调用 free(),您将调用 undefined behavior,因为指针不再由 malloc() 或函数族返回。

解决方法:你应该使用strcpy()来复制一个字符串的内容。

也就是说,

  1. Please see this discussion on why not to cast the return value of malloc() and family in C..
  2. int main()至少要int main(void)才符合标准。