我对此反应感到困惑.任何人都可以帮我解决这个问题,并指出我犯了错误的地方?键盘输出是" memory clobbered before allocated block"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s = (char *)malloc(10 * sizeof(char));
s = "heel";
printf("%s\n",s);
printf("%c\n",s[2]);
printf("%p\n",s);
printf("%d\n",s);
free(s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*per 11
你试图释放常量内存:
free(s); // cannot free constant "heel"
Run Code Online (Sandbox Code Playgroud)
你正在做的是分配一块内存并存储它的位置(char *s).然后你用一个字符串常量"heel"(内存泄漏)覆盖该引用,这不能是freed.要使其按预期运行,您应该将常量字符串复制到您分配的内存:
strcpy(s, "heel");
Run Code Online (Sandbox Code Playgroud)
以下是获取用户输入的示例:
char *input = malloc(sizeof(char) * 16); // enough space for 15 characters + '\0'
fgets(input, 16, stdin);
// do something with input
free(input);
Run Code Online (Sandbox Code Playgroud)