C编程 – 将指针返回到释放状态
发布时间:2020-12-16 09:29:06 所属栏目:百科 来源:网络整理
导读:我有一个函数foo(),它分配内存并返回它.我的标准做法是在我的主要功能结束时释放它吗? char* foo(){ char * p; p = malloc(sizeof(char) * 4); /* edit - thanks to msg board */ p[0] = 'a'; p[1] = 'b'; p[2] = 'c'; p[3] = '/0'; /* edit: thanks to the
我有一个函数foo(),它分配内存并返回它.我的标准做法是在我的主要功能结束时释放它吗?
char* foo(){ char * p; p = malloc(sizeof(char) * 4); /* edit - thanks to msg board */ p[0] = 'a'; p[1] = 'b'; p[2] = 'c'; p[3] = '/0'; /* edit: thanks to the msg board. */ return p; } int main(int argc,char *argv[]) { char * p2; p2 = foo(); printf("%s",p2); free(p2); return 0; } 解决方法
在main()结束时释放是正确的事情,是的.但是,您可能会考虑使用null来终止该字符串.对于所有“同一级别”的内存管理,可以说更为惯用的设计.就像是:
void foo(char *p) { p[0] = 'a'; p[1] = 'b'; p[2] = 'c'; p[3] = ' '; } int main(int argc,char **argv) { char *p2 = malloc(4); foo(p2); printf("%s",p2); free(p2); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |