Bug 97321 - add warning for pointer casts that may lead to aliasing violation when dereferenced
Summary: add warning for pointer casts that may lead to aliasing violation when derefe...
Status: RESOLVED WORKSFORME
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 10.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2020-10-07 14:17 UTC by nsz
Modified: 2020-10-07 14:35 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description nsz 2020-10-07 14:17:35 UTC
consider:

int f(unsigned char **);

int g(char *p)
{
    return f((unsigned char **)&p);
}

such code is almost surely wrong (if f dereferences its
argument) this is a common mistake and it seems gcc-11
will optimize such code more aggressively which can lead
to broken behavior, see bug 97264.

so it would be useful to simply warn about casts between
pointer types that cannot alias. e.g.:

"warning: dangerous cast from `char **` to `unsigned char **` can lead to aliasing violation [-Wpointer-cast]"

does not have to be in -Wall, but the current aliasing
warnings are too weak to catch bugs like in the example.
Comment 1 Richard Biener 2020-10-07 14:35:12 UTC
> gcc t5.c -O2 -Wstrict-aliasing=2
t5.c: In function 'g':
t5.c:5:32: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
    5 |     return f((unsigned char **)&p);
      |                                ^~

so it already works.