Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free a char* that will be returned?

Tags:

c

malloc

free

Say I have the function below :

char* fakeTrim(char* input) {
    char* temp = malloc(strlen(input));
    int count = 0;
    for(int i = 0; i < strlen(input); i++) {
        if(input[i] != ' ')
            temp[count++] = input[i];
    }
    temp[count] = '\0';
    return temp;
}

Does the temp cause any memory leakage? IF so, is it possible to free it before we return temp?

Thanks!

like image 864
user3471059 Avatar asked Dec 29 '25 19:12

user3471059


1 Answers

No, of course you can't free memory that belongs to the data you're returning. And indeed allocating memory within a utility function like this makes memory leaks extremely likely; since the caller won't see the function body, it will be very easy for her to forget to free it. There is a standard solution to this issue actually, and that is to make the caller allocate the memory himself:

void fakeTrim(const char* input, char* temp) {
    int count = 0;
    for(int i = 0; i < strlen(input); i++) {
        if(input[i] != ' ')
            temp[count++] = input[i];
    }
    temp[count] = '\0';
}

Now memory leaks are still possible but it's not 'your fault'--the caller should know to free memory that he allocates. Note the addition of const in the signature makes which argument is input, and which is output, clear.

Edit: Here's a use case:

const char* input = "Hello world";
char* temp = malloc(strlen(input)+1);
fakeTrim(input, temp);
// ... do something with temp
free(temp);
like image 62
Matt Phillips Avatar answered Dec 31 '25 08:12

Matt Phillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!