During a recent discussion (see comments to this answer), R.. recommended to never create aliases for pointer-to-const
types as you won't be able to deallocate the referenced objects easily in a conforming C program (remember: free()
takes a non-const
pointer argument and C99 6.3.2.3 only allows conversions from non-qualified to qualified).
The C language obviously assumes the existance of an owner for any allocated object, ie someone somewhere has to store a non-const
pointer to the object, and this someone is responsible for deallocation.
Now, consider a library allocating and initializing objects which are non-modifyable from user-space code, so function calls always return const
-qualified pointers.
Clearly, the library is the owner of the object and should retain a non-const
pointer, which is somewhat silly as the user already supplies a perfectly valid, but const
copy of the pointer on each library call.
To deallocate such an object, the library has to discard the const
qualifier; as far as I can tell, the following
void dealloc_foo(const struct foo *foo)
{
free((void *)foo);
}
is valid C; it would only be invalid if the foo
parameter were additionally restrict
-qualified.
However, casting away const
seems somewhat hack-ish.
Is there another way aside from dropping the const
from all return values of library functions, which would lose any information about object mutability?