tags:

views:

303

answers:

4

Hello. 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;
}
+11  A: 

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;
}
Luca Matteis
calloc zeroes out the memory, so there's no need for an extra memset or whatever (there _would_ be had @DalGr used malloc instead, but that's not what he did).
Alex Martelli
calloc sets the memory to zeroes
Adrian Panasiuk
I forgot about the implementation of calloc(); Thanks.
Luca Matteis
+3  A: 

Yes, you have to free it. Try valgrind to detect the leak.

Gábor Hargitai
+3  A: 

Yes. If you call calloc, malloc, new, etc. a call to a function that frees the memory must also be made.

Steve
+5  A: 

Since the applications ends right after printf, there's really no need to free it, since the application will do that for you when it dies. But yes, it's always good practice to free it.

Magnus Skog
I agree with you in principle, but its this kind of thinking that gets people into trouble. Especially beginners.
Steve