Path: ...!weretis.net!feeder9.news.weretis.net!news.quux.org!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: So You Think You Can Const? Date: Thu, 09 Jan 2025 23:40:52 -0800 Organization: None to speak of Lines: 46 Message-ID: <874j27qfp7.fsf@nosuchdomain.example.com> References: MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Fri, 10 Jan 2025 08:40:53 +0100 (CET) Injection-Info: dont-email.me; posting-host="e16be66d43b38b7ea574a81744fe375a"; logging-data="4091122"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18CGtMCkLdWVYG0GeyHWEWV" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:ccatjvG/sDPnlshkRPgxQTRpS7Q= sha1:aVlb1VkeKkbvEOYKoVTNfieuOeo= Bytes: 2970 Andrey Tarasevich 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.com void Void(void) { Void(); } /* The recursive call of the void */