views:

128

answers:

2

Can I use free for const char*? Will this cause any problems?

+2  A: 

No. 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".

unwind
I have the same structure`struct Account{ const char* strLastName; //Client's last name const char* strFirstName; //Client's first name int nID; //Client's ID number int nLines; //Number of lines related to account double lastBill; //Client's last bill for all lines List linesDataBase;};`I use malloc for creating and then trying to free memory of firstName and lastName so I receive from compiler warning
lego69
I tried this by malloc memory for a const char *. There were warnings, but everything worked fine. Why?
Jay
If the pointer passed to free is valid to be freed (i.e. it was returned from a call to `malloc` or related function) then any special book keeping area must be writeable. If the `malloc` return value was cast (from `void*`) to a `const char*` then so long as a valid prototype for `free` is in scope then the function call will cause the correct conversion back to `void *` and the call is valid.
Charles Bailey
The `const` keyword that is passed to function parameter is only a declarative statement. It tells the caller that the implementator promised to not modify the pointed memory. It has absolutely no bearing on the nature of the memory the pointer points to.
tristopia
-1 see Charles Bailey comment, he already gave the correct answer.
tristopia
+1  A: 

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