Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming - Return Pointer to Freed

Tags:

c

memory-leaks

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;
}
like image 601
Kevin Meredith Avatar asked May 08 '26 06:05

Kevin Meredith


1 Answers

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;
}
like image 173
Carl Norum Avatar answered May 10 '26 19:05

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!