char*之后无法释放内存

Jax*_*x-p 3 c free

当我尝试在程序结束时释放内存时,我遇到了问题.它一直在打破.你能告诉我问题在哪里吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 7

在你的代码中,通过说

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

后来,通过调用free()word,你调用未定义的行为,因为指针由一个不再退还malloc()或家庭的功能.

解决方案:您应该使用strcpy()复制字符串的内容.

那说,

  1. 请参阅此讨论,了解为什么不投出malloc()和家人的回报值C..
  2. int main()int main(void)至少符合标准.