用的codeblocks编译器
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str=(char *)malloc(6);
str="hello";
printf("%s\t%u\n",str,str);
str=(char *)realloc(str,21);
strcat(str,"world");
printf("%s\t%u",str,str);
free(str);
return 0;
}
输出结果:
debug时报错
请问是什么原因?
str="hello";
这个语句将字符串常量"hello"
的地址赋值给str
, 所以str
的地址改变为一个指向常量字符串的地址. 不是malloc
的地址, 所以free(str)
就会出错.可以改为: