This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Can offsetting a non-null pointer result in a null one?
- From: Jeff Law <law at redhat dot com>
- To: Liu Hao <lh_mouse at 126 dot com>, "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Tue, 14 Aug 2018 22:48:41 -0600
- Subject: Re: Can offsetting a non-null pointer result in a null one?
- References: <99f401a9-9419-819b-cbe0-b3b062c5372e@126.com>
On 08/14/2018 09:45 PM, Liu Hao wrote:
> 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?
I just don't think anyone's ever bothered to catch this case. I believe
there is a BZ which touches on this issue.
Jeff