https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109708
Bug ID: 109708
Summary: [c, doc] wdangling-pointer example broken
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: vries at gcc dot gnu.org
Target Milestone: ---
I ran into a Wdangling-pointer warning and decided to read the docs and try out
an example.
The first one listed is:
...
int f (int c1, int c2, x)
{
char *p = strchr ((char[]){ c1, c2 }, c3);
// warning: dangling pointer to a compound literal
return p ? *p : 'x';
}
...
It's not a complete example, x is missing a declared type and c3 is undeclared.
After fixing that (and adding the implicit "#include <string.h>"), we have an
example that compiles:
...
#include <string.h>
int f (int c1, int c2, int c3)
{
char *p = strchr ((char[]){ c1, c2 }, c3);
return p ? *p : 'x';
}
...
but no warning, not at O0, O1, O2 or O3:
...
$ gcc test.c -Wdangling-pointer=1 -c
$
...
After reading the description of the warning, I managed to come up with:
...
char
f (char c1, char c2)
{
char *p;
{
p = (char[]) { c1, c2 };
}
return *p;
}
...
which does manage to trigger the warning for O0-O3:
...
$ gcc test.c -Wdangling-pointer=1 -c
test.c: In function ‘f’:
test.c:10:10: warning: using dangling pointer ‘p’ to an unnamed temporary
[-Wdangling-pointer=]
10 | return *p;
| ^~
test.c:7:18: note: unnamed temporary defined here
7 | p = (char[]) { c1, c2 };
| ^
$
...
It might be worth mentioning that it's a C example, when using g++ we have:
...
$ g++ test.c -Wdangling-pointer=1 -c
test.c: In function ‘char f(char, char)’:
test.c:7:18: error: taking address of temporary array
7 | p = (char[]) { c1, c2 };
| ^~~~~~~~~~
...
BTW, note that the warning can be fixed by doing:
...
char
f (char c1, char c2)
{
char *p;
+ char c;
{
p = (char[]) { c1, c2 };
+ c = *p;
}
- return *p;
+ return c;
}
...