Sujet : Re: So You Think You Can Const?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 10. Jan 2025, 08:40:52
Autres entêtes
Organisation : None to speak of
Message-ID : <874j27qfp7.fsf@nosuchdomain.example.com>
References : 1 2 3 4
User-Agent : Gnus/5.13 (Gnus v5.13)
Andrey Tarasevich <
andreytarasevich@hotmail.com> writes:
On 01/09/25 12:12 AM, Julio Di Egidio wrote:
I do not understand that: `free` is changing the pointed data, so
how can `const void *` even be "correct"?
>
`free` is destroying the pointed data.
Right. In other words, it causes the pointed-to data to reach the end
of its lifetime. "Changing" the data generally means modifying its
value (that's what "const" forbids).
Given:
int *ptr = malloc(sizeof *ptr);
*ptr = 42;
printf("*ptr = %d\n", *ptr);
free(ptr);
After the call to free(), the int object logically no longer exists.
Also, the value of the pointer object ptr becomes indeterminate.
Attempting to refer to the value of either ptr or *ptr has undefined
behavior.
Having said that, it's likely that such an attempt will not be
diagnosed, and that the values of ptr and *ptr will be *appear* to be
the same before and after calling free(). (Though the memory management
system might update *ptr, depending on the implementation.) But this is
outside the scope of what C defines, and there are no guarantees of
*anything*.
Every object in C object model has to be created (when its lifetime
begins) and has to be eventually destroyed (when its lifetime
ends). This applies to all objects, including `const` ones
(!). Lifetime of a `const` objects also ends eventually, which means
that `const` object has to be destroyable. No way around it.
An object with static storage duration (either defined with the "static"
keyword or defined at file scope) has a lifetime that ends when the
program terminates. In a typical implementation, the destruction of
such an object doesn't do anything other than deallocating its memory.
[...]
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */