[Zlib-devel] Allow read-only data as input

Cosmin Truta cosmin at cs.toronto.edu
Tue Mar 29 11:33:28 EDT 2011


On Tue, Mar 29, 2011 at 10:32 AM, Sebastian Huber wrote:
>> Generally, there should be no need to change any surrounding code if
>> the lvalue changes from a non-const pointer to a const pointer.
>>
>> int *p;
>> int *q;
>> p = q;
>>
>> can be changed to
>>
>> const int *p;
>> int *q;
>> p = q;
>>
>
> Yes, but not q = p, or parameter_is_non_const(p) (like free()).  I don't
> think that
>
> free(z_steam.next_in)
>
> is a big deal since z_stream.next_in changes after processing and thus
> is in most cases not suitable to free something.

You can always go, safely, from non-const to const, but you cannot
generally go the other way.
If you want to use free(), or any other function that requires
non-const pointers, then you should *not* make those const, because
you would be breaching the Standard C rules of const correctness.

A function foo(const T *ptr) promises to not modify *ptr. On the other
hand, free(ptr) does not make such promises: quite the contrary,
free(ptr) all but guarantees that it will mess up your ptr. Even if
you do know that you no longer need something that's const, you should
go via the non-const route.

Consider:

const int *p;
int *q;

p = q;  // correct
q = p;  // incorrect
q = (int*)p;  // generally unsafe

#if 0
free(p); // as incorrect as q = p
free((int *)p); // as unsafe as q = (int*)p
#else
free(q); // correct
#endif

> I don't know if it is
> acceptable to break existing zlib user code, but the option to allow
> read-only input data without a cast would be nice.

I agree that an option to deal with legacy code might be useful, if
such need is demonstrated with concrete examples. However, I disagree
with introducing an option to allow circumventing the const
correctness rules. There is a very good reason why Standard C
disallows passing const objects to free(), or to other functions that
modify the arg pointer.

Best regards,
Cosmin




More information about the Zlib-devel mailing list