How do I correctly free something that is pointed to by a pointer to const?
Look at this:
struct pair{
void const * key;
void const * val;
};
Here I have a struct that is to be used for hash tables. I make them const because the keys are not supposed to change while they are inside a hash table. If the key is changed, that would mess up the table. This helped a lot, compilation would fail if I accidentaly modify the key. This is all good until I am finished with the pair and decide to free the key and val:
void free(void * ptr);
If I try to free key, compilation fails, because the prototype of free makes no guarantees of not modifying whatever is passed in, like this:
void free(void const * ptr);
Right now, I handle this by casting the pointer to non const, then free it:
void FREE(void const * ptr)
{
free((void *)ptr);
}
This lets me compile, but it looks evil.
After searching around, I found kfree:
void kfree(const void *objp);
But I can't use that, because it is part of linux, and not of the C standard.
Am I just being paranoid, and casting to non const is fine? Or is there another solution? Assuming struct pair is opaque, and key and val are always malloced and memcpy of argument pointers.






