c++中使用malloc(free)遇到的问题
结构体类型声明:structStudent{intstu_id;charstu_name[20];floatstu_score;intstu_count;Student*...
结构体类型声明:
struct Student
{
int stu_id;
char stu_name[20];
float stu_score;
int stu_count;
Student *next;
};
程序代码:
Student stu1[5] =
{
{1001,"Zhaoa",98.5,80,NULL},
{1002,"Qianb",78.5,50,NULL},
{1003,"Sunc",82.3,100,NULL},
{1004,"Lid",66.25,55,NULL},
{1005,"Zhoue",58.0,72,NULL}
};
stu1[0].next = &stu1[1];
stu1[1].next = &stu1[2];
stu1[2].next = &stu1[3];
stu1[3].next = &stu1[4];
stu1[4].next = NULL;
Student *ps = (Student *)malloc(sizeof(Student)*5); //malloc分配内存空间
memset(ps, '\0', sizeof(Student)*5);
if(NULL == ps)
{
cerr<<"malloc Student error!"<<endl;
return -1;
}
for(int j=0; j<5; j++)
{
(ps+j)->stu_id = stu1[j].stu_id;
strcpy((ps+j)->stu_name,stu1[j].stu_name);
(ps+j)->stu_score = stu1[j].stu_score;
(ps+j)->stu_count = stu1[j].stu_count;
(ps+j)->next = stu1[j].next;
}
free(ps);//将free放在这里,为何下面也能输出
for(; ps!=NULL; ps=ps->next)
{
cout<<ps->stu_id<<", "<<ps->stu_name<<", "<<ps->stu_score<<", "<<ps->stu_count<<endl;
}
//free(ps);
return 0;
输出结果(带乱码):
8464296, ? 98.5, 80
请高手解答,谢谢。 展开
struct Student
{
int stu_id;
char stu_name[20];
float stu_score;
int stu_count;
Student *next;
};
程序代码:
Student stu1[5] =
{
{1001,"Zhaoa",98.5,80,NULL},
{1002,"Qianb",78.5,50,NULL},
{1003,"Sunc",82.3,100,NULL},
{1004,"Lid",66.25,55,NULL},
{1005,"Zhoue",58.0,72,NULL}
};
stu1[0].next = &stu1[1];
stu1[1].next = &stu1[2];
stu1[2].next = &stu1[3];
stu1[3].next = &stu1[4];
stu1[4].next = NULL;
Student *ps = (Student *)malloc(sizeof(Student)*5); //malloc分配内存空间
memset(ps, '\0', sizeof(Student)*5);
if(NULL == ps)
{
cerr<<"malloc Student error!"<<endl;
return -1;
}
for(int j=0; j<5; j++)
{
(ps+j)->stu_id = stu1[j].stu_id;
strcpy((ps+j)->stu_name,stu1[j].stu_name);
(ps+j)->stu_score = stu1[j].stu_score;
(ps+j)->stu_count = stu1[j].stu_count;
(ps+j)->next = stu1[j].next;
}
free(ps);//将free放在这里,为何下面也能输出
for(; ps!=NULL; ps=ps->next)
{
cout<<ps->stu_id<<", "<<ps->stu_name<<", "<<ps->stu_score<<", "<<ps->stu_count<<endl;
}
//free(ps);
return 0;
输出结果(带乱码):
8464296, ? 98.5, 80
请高手解答,谢谢。 展开
2个回答
展开全部
free(ps);//将free放在这里,为何下面也能输出
free这后应该置NULL 不然会出现野指针
像下面这样
free(ps);
ps = NULL;
free这后应该置NULL 不然会出现野指针
像下面这样
free(ps);
ps = NULL;
追问
谢谢你!
我再想请教个问题:
Student stu1[5] =
{
{1001,"Zhaoa",98.5,80,NULL},
{1002,"Qianb",78.5,50,NULL},
{1003,"Sunc",82.3,100,NULL},
{1004,"Lid",66.25,55,NULL},
{1005,"Zhoue",58.0,72,NULL}
};
这段初始化stu1,我没有用malloc先申请内存,所以就没有用free释放,这样会不会造成这段空间一直没释放,出现内存泄露。函数返回return了,它会释放吗
追答
会自动释放 这种就不用管了
只有malloc出的 才free
看看这个 了解下吧
1、栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
2、堆区(heap)— 由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表。
3、全局区(静态区)(static)— 全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域, 未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统释放。
4、文字常量区 — 常量字符串就是放在这里的,程序结束后由系统释放 。
5、程序代码区— 存放函数体的二进制代码。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2012-05-20
展开全部
strcpy((ps+j)->stu_name,stu1[j].stu_name);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询