DalGr
DalGr

Reputation:

Will this leak memory?

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;
}

Upvotes: 4

Views: 912

Answers (5)

MastAvalons
MastAvalons

Reputation: 1141

memory leaks and free memory this is tricky problems. may be worth trying the debugger? I use deleaker for solving such problems.

Upvotes: 2

ralphtheninja
ralphtheninja

Reputation: 133008

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.

Upvotes: 5

Luca Matteis
Luca Matteis

Reputation: 29267

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;
}

Upvotes: 13

Steve
Steve

Reputation: 12004

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

Upvotes: 3

G&#225;bor Hargitai
G&#225;bor Hargitai

Reputation: 564

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

Upvotes: 3

Related Questions