转载于:https://blog.youkuaiyun.com/qq_40977765/article/details/89191053
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#pragma warning (disable:4996)
int main()
{
char *temp;
temp = (char *)malloc(sizeof(char));
printf("temp:");
scanf("%s", temp);
printf("%s", temp);
puts(temp);
free(temp);//这里会释放失败
printf("success\n");
getchar();
getchar();
return 0;
}
PS:#pragma warning (disable:4996)仅用在2017版VS中无视安全检查,getchar()用于暂停运行。
运行结果:
输入“123”能够正常输出“123”,但是free()函数不能正常执行。出现HEAP CORRUPTION DETECTED的错误。
原因:temp只向系统要求开辟一个空间,而实际上输入字符串超过了开辟的空间存贮量。
解决方法:使用malloc申请足够的空间。比如:temp = (char *)malloc(sizeof(char)+1);