函数返回的问题..

austinlui 2008-12-18 09:32:47
今天做数据结构作业。。。遇到点问题..
//这个是主函数里调用的语句..
PrintStudentList(Order(ShellSort(Copy(A,n), n), n), n);

被调用函数大致如下:
StudentList Copy(StudentList A, int n)
{
StudentList B = (StudentList)malloc(n*sizeof(student));
.....//A复制到B
return B;
}
StudentList ShellSort(StudenList A, int n);
StudentList Order(StudentList A, int n);
....

我想问的是Copy中的B在return 后,它的生存期不就结束了么?为什么我那样写程序还能运行?

..是不是那个copy函数的最后没有用free把malloc分配的空间给释放掉,就算是内存泄漏了..就算函数返回了,堆里的空间还是占用着是吧?所以外层函数ShellSort()Order()之类的还可以访问那个空间里的内容?
...全文
67 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ken_scott 2008-12-18
  • 打赏
  • 举报
回复
你返回的是值(又不是引用,在C++里不会出问题)在C里也应该不会吧

不过没有释放资源,却是不可取!
austinlui 2008-12-18
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lbh2001 的回复:]
引用 2 楼 austinlui 的回复:
我现在main函数里把某个函数里用malloc分配的而为有对应的free的内存给释放,可是vc报错..为什么?


你确定那个free的指针是对的,函数里用malloc分配的内存指针传回给main了吗


....
[/Quote]

这样..没试过...我之前写的函数是void类型的..然后给里面一个引用的指针malloc了空间..
lann64 2008-12-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 austinlui 的回复:]
我现在main函数里把某个函数里用malloc分配的而为有对应的free的内存给释放,可是vc报错..为什么?
[/Quote]
看你怎么用的。要取得正确的分配地址
lbh2001 2008-12-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 austinlui 的回复:]
我现在main函数里把某个函数里用malloc分配的而为有对应的free的内存给释放,可是vc报错..为什么?
[/Quote]

你确定那个free的指针是对的,函数里用malloc分配的内存指针传回给main了吗


char *f(void)
{
char *pt = malloc(8);
memset(pt, 0, 8);
return pt;
}

int main(void)
{
char *p;
p = f();
free(p);
return 0;
}
austinlui 2008-12-18
  • 打赏
  • 举报
回复
我现在main函数里把某个函数里用malloc分配的而为有对应的free的内存给释放,可是vc报错..为什么?
lbh2001 2008-12-18
  • 打赏
  • 举报
回复
[Quote=引用楼主 austinlui 的帖子:]
今天做数据结构作业。。。遇到点问题..
//这个是主函数里调用的语句..
PrintStudentList(Order(ShellSort(Copy(A,n), n), n), n);

被调用函数大致如下:
StudentList Copy(StudentList A, int n)
{
StudentList B = (StudentList)malloc(n*sizeof(student));
.....//A复制到B
return B;
}
StudentList ShellSort(StudenList A, int n);
StudentList Order(StudentList A, int n);
....

我想…
[/Quote]

malloc后没有对应的free,则那块内存就没有释放,你的想法是正确的

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧