Sujet : Re: So You Think You Can Const?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 11. Jan 2025, 23:50:38
Autres entêtes
Organisation : None to speak of
Message-ID : <87v7ulj77l.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6 7 8
User-Agent : Gnus/5.13 (Gnus v5.13)
Julio Di Egidio <
julio@diegidio.name> writes:
On 11/01/2025 12:14, David Brown wrote:
On 10/01/2025 19:56, Keith Thompson wrote:
<snip>
The idea was to place the emphasis on "free" changing the pointer,
rather than the data pointed to.
>
I feel I am still altogether missing the point.
>
Is my understanding correct that when freeing a pointer: 1) the
pointer value, i.e. the address it holds, does not change; OTOH, 2)
the pointed-to object does change, in the sense that it is marked
unusable (and, supposedly, made available to re-allocation)?
>
Moreover, while the pointer value has not changed, it is in fact
changed in the sense that it has become invalid, namely the pointer
cannot be used (validly dereferenced) anymore. Not just that, but
*every* pointer to the same object, i.e. holding the same address, has
become invalid.
>
All that considered, how isn't `void free(void *p)`, i.e. with no
const qualifiers anywhere, the only reasonable signature?
It is.
The current declaration `void free(void *p)` implies that the free
function does not promise to modify the data pointed to by p. In fact
it may or may not do so. (No program can tell whether the data is
modified without undefined behavior.)
`void free(const void *p)` would imply a promise by free that it will
not modify that data. Since it does so in some implementations and
since any attempt to access that data would have undefined behavior,
that would not be useful.
In `void free(void *const p)`, the "const" would be nearly meaningless.
p is a parameter, a local object in the implementation of free. The
"const", if it appears in the definition (assuming free() is implemented
as a C function), would be a promise not to modify that local object --
something that should be of no relevance to callers. In the
declaration, it means nothing.
The visible declaration of free does not, and cannot, communicate all
the relevant information about it. The allocated data reaches the end
of its lifetime, and the pointer value passed to free therefore becomes
indeterminate. The same thing happens with a pointer to a local object
when that object reaches the end of its lifetime:
{
int *p;
{
int n = 42;
p = &n;
}
printf("p = %p\n", (void*)p); // undefined behavior
}
C's declaration syntax can't express those effects, which is why they're
stated explicitly in the standard.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */