Re: AW: A: a new bug to old plain C

J Decker via Gcc-help <[email protected]>
Newsgroups gmane.comp.gcc.help
Message-ID <CAA2GJqU_hXKOZUd+fp_f1Xnw=UhVwHZ6UAFQt3WbqA2pFx+c1Q@mail.gmail.com>
I'm glad to see someone trying to champion this cause.... because the
usefulness of inheriting const ( maybe things like volatile too)
automatically, at any level offers protections, and posits intention to not
cause changes.

This looks like a good place to jump in....


    int
    main(void)
      {
        const char* s1 = "meow";
        void* p = &s1;
        char** pp = p;   // implicit conversion from `void*` drops qualifier
        **pp = 'b';
      }

if you deliberately want to mess yourself up, just cast some things.  If
you want to undermine the advertised promise not to change data passed to a
function, so be it - there's memcpy too.

There's been so many examples of 'well I could use such a behavior to do
this bad thing'.  It was my understanding of the C standard from K&R days,
was that pointers could inherit const, but not lose const... I was sad to
see that there was a bizarre behavior of '" char const *const * argv =
(char**)argv_"  didn't work.  I just wanted const so I didn't incidentally
change things... on a function interface, (contrary to consensus about
specific meaning of what const is and implies) is just a notation that a
function won't change the content passed.  Again, there's plenty of ways
that could be worked around.

I honestly haven't seen a good argument as to why you can't just inherit
const.  It doesn't mean the data underlaying it doesn't change...
voltatile const is a good example ... a fetch-only sort of variable and
read always, don't cache the 'const' in a register.




On Fri, Dec 5, 2025 at 12:29 AM LIU Hao via Gcc-help <[email protected]>
wrote:

> 在 2025-12-5 16:10, [email protected] 写道:
> > Refering to that example
> >
> > int compare (const void *a1, const void *b1) {
> >    char *const *a = a1;
> >     ...
> >
> > Here a and a1 have a different types.
> >
> This conversion is allowed due to the special rule about pointer-to-void,
> which can indeed be exploited
> to modify a const-qualified object (https://gcc.godbolt.org/z/qa7qM9W8Y):
>
>     int
>     main(void)
>       {
>         const char* s1 = "meow";
>         void* p = &s1;
>         char** pp = p;   // implicit conversion from `void*` drops
> qualifier
>         **pp = 'b';
>       }
>
> It can also be exploited in C++ to modify a const-qualified object without
> `const_cast`
> (https://gcc.godbolt.org/z/cKo3Ghfaq). It's nothing about safety; it's
> only about what is defined and
> what is not. Anything that is not defined is undefined. There are all
> kinds of holes in the standard.
>
>
>
> --
> Best regards,
> LIU Hao
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.