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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With