const, the errors framework, and -Wcast-qual
ghudson@MIT.EDU
ghudson at MIT.EDU
Sun Nov 1 17:55:22 EST 2009
My C experience leads me to believe that const pointers should be used
for (1) pointers to non-heap-allocated memory (C string literals,
stack memory, etc.) which you don't want changed, or (2) aliases to
heap-allocated memory owned by some other, non-const pointer, which
you don't want changed through the alias. In particular, it's my
understanding that const pointers should *not* be used for pointers
which will be used to free memory; destroying is a form of
modification, so if a pointer owns a piece of heap-allocated memory,
it has to be non-const even if that memory is intended to be immutable
until freed.
The errors framework doesn't agree with this principal. struct
errinfo contained a const pointer to memory it owns, although I just
changed that. krb5int_get_error and krb5_get_error_message return
const pointers even though those pointers are used to free memory.
The latter function is part of our API, although I don't know if it
would be a problem to change it to return char *, since that shouldn't
break any calling code.
I don't want to go on a crusade if I'm out of step with the community
on this. I can find stuff like
http://bytes.com/topic/c/answers/217935-passing-const-void-free (which
is more of an argument than a refernce) and
https://barnowl.mit.edu:444/wiki/const (which can't possibly be
authoritative since it was written by someone yonuger than I am), but
no Voice of Authority. So, here is a change to tell me that I am
educated stupid about this.
On a related and equally nitpicky note, I would like to remove
-Wcast-qual from our gcc warning set. Because we make heavy use of
krb5_data in our code base, we have a lot of cases where we
deliberately de-constify a pointer in order to fit into a krb5_data
value for use by some function which won't modify the memory (like
input to krb5_c_encrypt). I don't think it does us a big service to
identify places where people are deliberately circumventing const for
a reason such as this, when we usually can't fix it.
More information about the krbdev
mailing list