Can I use free
for const char*
? Will this cause any problems?
views:
128answers:
2No. By it's nature, free()
needs the freedom to write into the given memory, to do "book keeping". This is why it's defined to take a non-const
pointer.
As others have pointed out, this doesn't mean that it can't work; C can drop the const
-ness of a pointer and let the function run as if it was called without const
. The compiler will warn when that happens though, which is why I consider it to "cause problems".
If the pointer was allocated yes. You'll get a warning, but you've got one already when you allocated it.
I often use const char *
in my structs when I want to make sure that noone writes in them between the allocation and the release. There's often the case that you create dynamicly a string that is immutable for its lifetime and if you call it with a function with side effects (strtok
) you can get in trouble. By declaring it const
you can at least get warned in that case.
const char *msg;
asprintf((char *)&msg, "whatever" ...);
...
strtok(msg, ","); // Will generate a warning
...
free((char*)msg);