Question

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!

Was it helpful?

Solution

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

OTHER TIPS

No, you can only free the allocated memory when you no longer need to refer to it, which means that the caller needs to free the returned value (and you should mention this in the documentation for the function).

By the way, you will end up with an out-of-bounds array reference on temp[count] = '\0'; if your input string has no spaces in it, so you should allocate one more byte. (And trim doesn't usually remove internal spaces, but perhaps that is why you called it fakeTrim.)

Yes, Indeed temp will cause memory leakage.

However, I have an alternative solution for a requirement of yours. You can make use of a dynamic variable in the caller function by using pass by reference and later free it from the caller function itself (No need to free it from the called function). Please see below:

void main()
{
        char *test;

        setVal(test);
        puts(test);
        if(test){
                free(test);
                test = NULL;
        }
}
void setVal(char **data)
{
        char retry[100]="This is test";
        char *ret;

        ret = malloc((strlen(retry))*sizeof(char));
        if(ret == NULL)
                exit(1);
        strncpy(ret, retry, strlen(retry));

        *data = ret;
}

If you are still not satisfied. Use the sample codes I have provided with VALGRIND to see if there is any memory leakage.

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top