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?
expression
, but what if had been allocated on the stack, or a string literal? You should let the caller decide what to do with this. – Picco