首页 新闻 会员 周边

关于堆区释放内存问题

0
[已解决问题] 解决于 2015-05-21 18:15
#include "stdio.h"
#include "stdlib.h"

typedef struct _teacher
{
    char name[10];
    int age;
    char *title;
}Teacher;

int freeTea(Teacher *t1)
{
    if(t1==NULL)
    {
        return -1;
    }
    //t1->title = "World!";  可以修改title的值为什么不能释放内存?
    free(t1->title);
    t1->title = NULL;
    return 0;
}

int main()
{
    Teacher tVar1;
    
    tVar1.title = (char *)malloc(100);
    tVar1.title = "Heelo!";
    
    printf("%s", tVar1.title);
    
    if(tVar1.title!=NULL)
    {
        freeTea(&tVar1);
    }
    
    system("pause");    
    return 0;
}

本意: 在主函数malloc一块内存给tVar1.title一块内存,在freeTea中free()这块内存

现实: 断了....这是为什么呢? 在free()函数中明明可以修改这块内存的值,却不能释放

求解答,谢谢,勿喷

ariclee的主页 ariclee | 菜鸟二级 | 园豆:227
提问于:2015-05-16 17:32
< >
分享
最佳答案
0

指针指向问题!!!!你都指向"hello"常量区去了~~!!哪来的释放!!

ariclee | 菜鸟二级 |园豆:227 | 2015-05-16 18:02
其他回答(1)
0

tVar1.title = "Heelo!";

修改改为

strcpy(tVar1.title, "Heelo");

 

试试看

lixiong | 园豆:202 (菜鸟二级) | 2015-05-17 01:34

嗯 之前已经解决了,哈哈,是因为指向常量区去了,修改不了!

支持(0) 反对(0) ariclee | 园豆:227 (菜鸟二级) | 2015-05-18 18:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册