https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67535

--- Comment #6 from Vittorio Zecca <zeccav at gmail dot com> ---
The cost of adding "if(base_name_len)" is two x86-64 machine instructions

        cmpl    $0, -20(%rbp)
        je      .L2

Six instructions follow then

        call memcpy

which is not exactly a NOP even with base_name_len==0

In my opinion two machine instructions to avoid a useless and undefined memcpy
are a bargain.

It is not undefined behaviour to pass a NULL pointer to an arbitrary function,
but it is undefined to pass it to memcpy.

And it seems to me that after
memcpy(dest,src,len)

the statement "if(src)" is always TRUE because the optimizer assumes src!=NULL

The following is from https://gcc.gnu.org/gcc-4.9/porting_to.html

Null pointer checks may be optimized away more aggressively

GCC might now optimize away the null pointer check in code like:


  int copy (int* dest, int* src, size_t nbytes) {
    memmove (dest, src, nbytes);
    if (src != NULL)
      return *src;
    return 0;
  }

The pointers passed to memmove (and similar functions in <string.h>) must be
non-null even when nbytes==0, so GCC can use that information to remove the
check after the memmove call. Calling copy(p, NULL, 0) can therefore deference
a null pointer and crash.

The example above needs to be fixed to avoid the invalid memmove call, for
example:


    if (nbytes != 0)
      memmove (dest, src, nbytes);

This optimization can also affect implicit null pointer checks such as the one
done by the C++ runtime for the delete[] operator.

Reply via email to