本文介绍了C程序设计 - 返回指向弗里德的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数foo(),它分配内存,并返回它。它是标准的做法让我在我的主要函数的最后释放呢?

 的char * foo的(){
 字符* P; P =的malloc(sizeof的(字符)* 4); / *编辑 - 感谢味精板* /
 P [0] ='一';
 P [1] ='B';
 P [2] ='c'的;
 P [3] ='/ 0'; / *编辑:感谢味精板。 * / 回磷;
}INT主(INT ARGC,CHAR *的argv [])
{
 字符* P2; P2 = foo的(); 的printf(%S,P2); 免费(P2); 返回0;
}


解决方案

年底舷的main()是做正确的事情,是的。你可能会想空终止该字符串,虽然。更惯用的设计是做所有的内存管理处于同一水平,可以这么说。是这样的:

 无效美孚(字符* P)
{
  P [0] ='一';
  P [1] ='B';
  P [2] ='c'的;
  P [3] ='\\ 0';
}INT主(INT ARGC,字符** argv的)
{
  字符* P2 =的malloc(4);
  富(P2);
  的printf(%S,P2);
  免费(P2);
  返回0;
}

I have a function, foo(), that allocates memory and returns it. Is it standard practice for me to free it at the end of my main function?

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;
}
解决方案

Freeing at the end of main() would be the correct thing to do, yes. You might think about null terminating that string, though. A more idiomatic design is do to all the memory management "at the same level", so to speak. Something like:

void foo(char *p)
{
  p[0] = 'a';
  p[1] = 'b';
  p[2] = 'c';
  p[3] = '\0';
}

int main(int argc, char **argv)
{
  char *p2 = malloc(4);
  foo(p2);
  printf("%s", p2);
  free(p2);
  return 0;
}

这篇关于C程序设计 - 返回指向弗里德的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 09:00