首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C语言 malloc/free 请问

2012-02-09 
C语言 malloc/free 请教我编写了如下代码[codeC/C++][/code]#include stdio.hstruct student{char *nam

C语言 malloc/free 请教
我编写了如下代码[code=C/C++][/code]#include <stdio.h>

struct student
{
char *name;
int score;
int glass;
};

typedef struct student sstudent;
typedef struct student *pstudent;
int main(int argc, char *argv[])
{
pstudent stu1 = NULL;
stu1 = ( pstudent ) malloc(sizeof( sstudent));
if ( stu1 == NULL)
{
printf(" malloc stu1 failed");
exit(1);
}
stu1 ->name = (char *)malloc(20 * sizeof(char));
strcpy( stu1 ->name , "fafasfasfsafsafsafsa");
stu1 -> score = 1;
stu1 -> glass = 5;
printf("Hello, world%s\n", stu1 -> name);
free( stu1 );
return 0;
}

现在我想问的是我已经free掉了 stu1,但是我仍然用malloc申请了堆空间 stu1->name ,我想问的是我free掉了stu1 的同时用malloc 申请的stu1 ->name 的空间也free掉了吗 谢谢了

[解决办法]
没有...
[解决办法]
stu1 ->name = (char *)malloc(21 * sizeof(char)); //这里长度改为21
strcpy( stu1 ->name , "fafasfasfsafsafsafsa"); //因为这里有20个字符 最后还有个'\0'

[解决办法]
要分别free,free函数并不了解,或者说并不关心你的结构的实际组成,只是简单的释放对应的空间而已。
建议写一个init函数来初始化你的结构
写一个destroy函数来销毁你的结构

[Quote=引用:]
我编写了如下代码[code=C/C++][/code]#include <stdio.h>

struct student
{
char *name;
int score;
int glass;
};

typedef struct student sstudent;
typedef struct student *pstudent;
int main(int argc, c……
[/Quote]

热点排行