I have a question about the following function and about memory allocation.
char *strjoin(char const *s1, char const *s2)
{
char *s3;
s3 = NULL;
if (s1 && s2)
{
s3 = (char *)malloc(sizeof(char) * (strlen(s1) + strlen(s2) + 1));
if (!s3)
return (NULL);
strcpy(s3, s1);
strcat(s3, s2);
}
return (s3);
}
int main()
{
char *s1 = "my favorite animal is";
char *s2 = " ";
char *s3 = "the nyancat";
char *res = strjoin(strjoin(s1, s2), s3);
}
The strjoins doc is as follows:
Allocates (with malloc(3)) and returns a “fresh” string ending with ’\0’, result of the concatenation of s1 and s2. If the allocation fails the function returns NULL.
In the main function, the function calls itself on this line:
char *res = strjoin(strjoin(s1, s2), s3);
Since memory is being allocated in the strjoin(s1, s2) but never assigned to anything, and it is being used in the outer function call, but never freed technically, does that memory just leak and go unused?