If I have this function foo() and I’m calling it from another function foo2(); must I free the memory in the calling function like this?
char *foo(char *str1){
char *str2;
str2 = malloc((sizeof(char) * strlen(str1)) + 1);
memcpy(str2, str1, strlen(str1) + 1)
return str2;
}
void foo2(void){
char *str1 = "Hello world!"
char *str2;
str2 = foo(str1);
...some stuff
free(str2); //Should I do this here?
}
Yes, it is right.
foo()allocates some memory and it must be freed by the caller. It’s not a very good design but it works. It could be better iffoo()accepts two parameters: output buffer and its size.If output is
NULLthe required size is written inbufferSizebyfoo().