Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* and free()

Given the next code example, I'm unable to free the parameter const char* expression:

// removes whitespace from a characterarray
char* removewhitespace(const char* expression, int length)
{
    int i = 0, j = 0;
    char* filtered;
    filtered = (char*)malloc(sizeof(char) * length);
    while(*(expression + i) != '\0')
    {
        if(!(*(expression + i) == ' '))
        {
            *(filtered + j) = *(expression + i);
            j++;
        }
        i++;
    }
    filtered[j] = '\0';
    free(expression); //this doesn't seem to work
    return filtered;
}

Before I return this function, I try to free the data in the expression parameter but I can't seem to free it.
I think it is probably because it is a constant, but I learned that a character array in C always should be a constant.

The error message I get is at the line with free(expression) and the message is:
expected void* but argument is of type const char * - compiler error

How do I discard the memory that the data expression contains?

like image 491
Marnix v. R. Avatar asked Jun 15 '12 19:06

Marnix v. R.


2 Answers

If it's a constant, that implies that it shouldn't be deleted, because it wasn't allocated: the caller could easily have passed a stack-based array to your method, and freeing it would be a bad thing.

The most common convention is that whatever code allocates some data should free the data. It's really not your routine's responsibility to free that argument since it has no way of knowing if that's even a legitimate thing to do.

like image 56
Ernest Friedman-Hill Avatar answered Sep 30 '22 10:09

Ernest Friedman-Hill


If you really want to have a function like this - taking a heap pointer, freeing it and in spite returning another heap pointer - you should document it very well.

Besides, you shouldn't make expression a const char*, because that doesn't match, as you see. char* should be fine, however.

like image 43
glglgl Avatar answered Sep 30 '22 08:09

glglgl