当我尝试在程序结束时释放内存时,我遇到了问题.它一直在打破.你能告诉我问题在哪里吗?
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)
在你的代码中,通过说
word = str1;
Run Code Online (Sandbox Code Playgroud)
malloc()-ed指针后来,通过调用free()上word,你调用未定义的行为,因为指针由一个不再退还malloc()或家庭的功能.
解决方案:您应该使用strcpy()复制字符串的内容.
那说,
malloc()和家人的回报值C..int main()应int main(void)至少符合标准.