Liste des Groupes | Revenir à cl c |
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.
[...]
Les messages affichés proviennent d'usenet.