[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Tinycc-devel] Warning message about string assignment
From: |
Stefanos |
Subject: |
Re: [Tinycc-devel] Warning message about string assignment |
Date: |
Sun, 25 Apr 2021 14:34:48 +0300 |
On Sun, 25 Apr 2021 03:03:40 +0200
Vincent Lefevre <vincent@vinc17.net> wrote:
> On 2021-04-25 03:08:44 +0300, Stefanos wrote:
> > I use `tcc version 0.9.27 - 1432574 (x86_64 Linux)` and the code I'm
> > testing is:
> >
> > #include <stdio.h>
> > #include <string.h>
> >
> > int main(void)
> > {
> > char *s = "Hello, world!";
> > printf("String length is %zu characters long.\n", strlen(s));
> > }
> >
> > I execute it with the following command:
> >
> > tcc -Wall -std=c11 -o test_strlen test_strlen.c
> >
> > The warning is
> >
> > tmp.c:6: error: assignment discards qualifiers from pointer target type
> >
> > With GCC and Clang does not throw any warning message.
> >
> > The command I used for both is:
> >
> > gcc -Wall -Wextra -Wpedantic -std=c11 -o test_strlen test_strlen.c
> > clang -Wall -Wextra -Wpedantic -std=c11 -o test_strlen test_strlen.c
>
> zira:~> gcc -Wwrite-strings -o test_strlen test_strlen.c
> test_strlen.c: In function ‘main’:
> test_strlen.c:6:13: warning: initialization discards ‘const’ qualifier from
> pointer target type [-Wdiscarded-qualifiers]
> 6 | char *s = "Hello, world!";
> | ^~~~~~~~~~~~~~~
>
> Here's what the GCC man page says:
>
> -Wwrite-strings
> When compiling C, give string constants the type "const char[length]"
> so that copying the address of one into a non-"const" "char *" pointer
> produces a warning. These warnings help you find at compile time code
> that can try to write into a string constant, but only if you have
> been very careful about using "const" in declarations and prototypes.
> Otherwise, it is just a nuisance. This is why we did not make -Wall
> request these warnings.
>
> This allows one to detect buggy code like
>
> #include <string.h>
>
> int main(void)
> {
> char *s = "Hello, world!";
> memcpy (s, "foo", 4);
> }
>
> zira:~> gcc -o test_strlen test_strlen.c
> zira:~> ./test_strlen
> zsh: segmentation fault (core dumped) ./test_strlen
>
I had the impression that `-Wall -Wextra -Wpedantic` would include this specific
flag by default, but seems like it didn't.
Both GCC and Clang fail to detect the issue without the `-Wwrite-strings` flag.
Thank you Vincent for the valuable information; I learned something important
today!
Cheers mate.