This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Can offsetting a non-null pointer result in a null one?
- From: Liu Hao <lh_mouse at 126 dot com>
- To: "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Wed, 15 Aug 2018 11:45:51 +0800
- Subject: Can offsetting a non-null pointer result in a null one?
Dear GCC people,
At the moment, with GCC 8.2, I compile the program
```
int foo(const char *p)
{
if(p == 0)
return 2;
const char *q = p + 1;
if(q == 0)
return 1;
return 0;
}
```
using
```
gcc-8 test.c -Wall -Wextra -Wpedantic -O3 -S
```
and get the following assembly (with irrelevant directives stripped out):
```
foo:
testq %rdi, %rdi
je .L3
xorl %eax, %eax
cmpq $-1, %rdi
sete %al
ret
.L3:
movl $2, %eax
ret
```
My question is that, when the first `if` is not taken, i.e. when `p` is
not null, is it possible that after adding 1 to `p` would result in a
null `q`? Clang has been assuming that the result can't be null and
optimize out the second `if` statement for years, but GCC is still
emitting a check there. Are there any special reasons that prevent GCC
from optimizing code this way?
--
Best regards,
LH_Mouse