c语言的空间释放问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 00:28:29
void main()
{
char *str = (char *)malloc (10*sizeof(char));;
str="hello world";
printf(str);
free(str);

}

上面代码的free(str),释放有问题,不知道为什么,希望能得到个好的答案~

#include <malloc.h>
#include <string.h>
#include <stdio.h>

void main()
{
char *str = (char *)malloc (20*sizeof(char));//扩大size 到20
//str="hello world"; //因为这里指向了这个常量
strcpy(str,"hello world");//这里我们只拷贝过来,就行
printf(str);
free(str); //free常量指针?肯定错

}

str="hello world"; 不能这样写

应该用:

strcpy(str,"hello world");

还有"hello world"的长度已经超过10了,分配空间时,应多分配一些

char *str = (char *)malloc (10*sizeof(char));; 后面多了个分号。

我的机子上可以运行啊