How can I free a const char*
? I allocated new memory using malloc
, and when I\'m trying to free it I always receive the error \"incompatible pointe
I think even if you cast the pointer to a non-const, the result of free will depends on the implementation. Normally const was designed for variable that you don't want to modify !!
I could be wrong but I think the problem lies in const
. Cast the pointer to non-const like:
free((char *) p);
Because with const
you say: Don't change the data this pointer points to.
Your code is reversed.
This:
char* name="Arnold";
const char* str=(const char*)malloc(strlen(name)+1);
Should look like this:
const char* name="Arnold";
char* str=(char*)malloc(strlen(name)+1);
The const
storage type tells the compiler that you do not intend to modify a block of memory once allocated (dynamically, or statically). Freeing memory is modifying it. Note, you don't need to cast the return value of malloc(), but that's just an aside.
There is little use in dynamically allocating memory (which you are doing, based on the length of name
) and telling the compiler you have no intention of using it. Note, using meaning writing something to it and then (optionally) freeing it later.
Casting to a different storage type does not fix the fact that you reversed the storage types to begin with :) It just makes a warning go away, which was trying to tell you something.
If the code is reversed (as it should be), free()
will work as expected since you can actually modify the memory that you allocated.
It makes no sense to malloc a pointer to const, since you will not be able to modify its contents (without ugly hacks).
FWIW though, gcc just gives a warning for the following:
//
// const.c
//
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *p = malloc(100);
free(p);
return 0;
}
$ gcc -Wall const.c -o const
const.c: In function ‘main’:
const.c:8: warning: passing argument 1 of ‘free’ discards qualifiers from pointer target type
$
What compiler are you using ?
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer; free
takes a void*
, not a const void*
:
free((char*)str);
You cannot free const char *
because it is const
. Store pointers received from malloc
in non-const pointer variables, so that you can pass them to free
. You can pass char *
arguments to functions taking const char *
arguments but opposite is not always true.
void foo (const char *x);
char *ptr = malloc (...);
foo (ptr);
free (ptr);