Will this leak memory?

c, malloc, string

Solution

Yes you need to free it.

Probably something like:

int main(){
    char *s = StrCat("HELLO ", "WORLD");
    printf("String: %s\n", s);
    free(s);
    return 0;
}

Problem

I made a small function to catenate strings and return the combined string. However since I assign memory to a third variable in the function, will the memory be freed when the function finishes or will it stay there, requiring me to free it later? and if I need to free it, what's the most stylish solution to do it? Here's the test code. It works, but I can't tell if that memory is freed or not with my tools. ``` #include <stdio.h> #include <math.h> #include <string.h> char * StrCat(const char *st1, const char *st2){ char *string = calloc((strlen(st1) + strlen(st2) + 1), sizeof(char)); strcat(string, st1); strcat(string, st2); return string; } int main(){ printf("String: %s\n", StrCat("HELLO ", "WORLD")); return 0; } ```

Original source