C Programming - Returns a pointer to Freed

I have a foo () function 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;
}
+3
source share
8 answers

Release at the end main()would be right, yes. However, you might think about the null termination of this line. A more idiomatic design, so to speak, refers to all memory management “on the same level”. Sort of:

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;
}
+6
source

“Standard practice,” if there is such a thing, is to free up memory as soon as you are done with it.

, , , - , , - - , malloced memory .

+1

, " ", free() memeory.

: new_foo() delete_foo(), :

char* new_foo()
{
    char * p;
    p = malloc(sizeof(int) * 4);
    /* ... */
    return p;
}

void delete_foo(char* p)
{
    free(p);
}

int main()
{
    char * p2;
    p2 = new_foo();
    /* ... */
    delete_foo(p2);
    return 0;
}

, , .

0

, . , , .

, , , , .

0

malloc (sizeof (int) * 3) 3 char?

0

, ( main()).

:

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

 return ;
}

int main(int argc, char *argv[])
{
 char * p2;

 p = malloc(sizeof(int) * 3);
 foo(p2);

 printf("%s", p2);    

 free(p2);

 return 0;
}
0

- , malloc's/free's. , , , malloc. , (, , ).

, .

0

, , , . , , , .

  • : malloc free. , - , main , free.

  • : - . - region , . , , ( ).

0

Source: https://habr.com/ru/post/1758446/


All Articles