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

Pedro Alves pedro at codesourcery.com
Wed Mar 30 06:47:48 EDT 2011


On Tuesday 29 March 2011 16:33:28, Cosmin Truta wrote:
> 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.
> 

There's nothing in any C standard that prohibits casting the const-ness
out of a pointer in order to free what it points to.  Provided
that the pointer points at an object whose storage was allocated with
malloc, calloc or realloc, it's legal.
Object lifetime and pointer constness are different things.  A const
pointer simply forbids modifying the underlying memory through _that_
particular pointer.

This is undefined, as it tries to deallocate a non-allocated object:

   const char conststr[] = "Hello world";
   free ((void *) conststr);

This is legal:

   const char *str = malloc (10);
   free ((void *) str);

The latter `free' ends the lifetime of the object returned
by the previous `malloc'.  The value of a pointer becomes
indeterminate when the object it points to reaches the end of
its lifetime.  Any uses of `str's old value after the free
are undefined.

-- 
Pedro Alves




More information about the Zlib-devel mailing list