Re: Cast "const char *" pointers to "char *" to avoid compiler warnings.

Jeffrey Walton <[email protected]>
Newsgroups gmane.comp.lib.newlib
Message-ID <CAH8yC8=DesWBjqYyzDdSDDfkseP_7NUFQsmMa1ifHmDz_QsVZg@mail.gmail.com>
On Tue, Oct 2, 2018 at 5:10 AM Christophe Lyon
<[email protected]> wrote:
>...  (In a very quick look at locale.c, for example,
> > locale can definitely be written to--it is definitely not const. This implies
> > that the const on new_locale is what is wrong.)
>
> I did have this "very quick look at locale.c" before writing the
> patch, and not adding
> the cast at the assignment point means removing "const" from __loadlocale()
> prototype:
> char *__loadlocale (struct __locale_t *loc, int category, const char
> *new_locale)
> which in turn has a significant impact on the callers which I hope
> people familiar
> with this area can confirm, or not.

As I understand it, you can only cast const away if the [original]
object is in fact non-const.

OK:

    void foo(const char* buff)
    {
        ((char*)buf)[0] = '\0';
    }

    char bar[10] = {0};
    foo(bar);

Not OK:

    void foo(const char* buff)
    {
        ((char*)buf)[0] = (char)1;
    }

    const char bar[10] = {0};
    foo(bar);

The tricky part is finding the original object.

I don't know if there is a sanitizer to help find these violations,
but I have often wondered about one.

Jeff
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.