Search code examples
c++gcc-warning

How to fix warning "the compiler can assume that the address of 'object' will never be NULL"


I use gcc8 to compile this code:

#include <iostream>

class person
{
    public:
        virtual void setage()=0;
};

void test(person &object)
{
    if (&object == NULL) {
        std::cout << "NULL object1" << std::endl;
    }

    if (!(&object)) 
    {
        std::cout << "NULL object1" << std::endl;
    }
}

int main()
{
    person *object=NULL;
    person &object1=*object;

    test(object1);
}

Then, two warnings come out after compiling and running:

$g++ -std=c++14 -pthread -fgnu-tm -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm -latomic -lstdc++fs && ./a.out

main.cpp: In function 'void test(person&)':

main.cpp:11:17: warning: the compiler can assume that the address of 'object' will never be NULL [-Waddress]

 if (&object == NULL) {

             ^

main.cpp:15:18: warning: the compiler can assume that the address of 'object' will never be NULL [-Waddress]

 if (!(&object))

              ^

main.cpp:15:5: warning: nonnull argument 'object' compared to NULL [-Wnonnull-compare]

 if (!(&object))

 ^~

main.cpp:11:5: warning: nonnull argument 'object' compared to NULL [-Wnonnull-compare]

 if (&object == NULL) {

 ^~
  1. Why is the address of object in function test not NULL even passing a NULL reference value to it?
  2. It seems that reference object in function test can never be NULL, so we can just remove the code if (&object == NULL){...} and if (&object == NULL) {...} to avoid these two warnings, right?

Thanks for hints.


Solution

  • References are never null in a well-formed C++ program. The only valid way to initialize a reference is to bind it to a valid object. The only way a "null reference" may happen is if one derefernces a null pointer, as you have. But then the behavior of your program is undefined even before you check &object == NULL. The bug is in the code that passes the "null reference", and it must be fixed there.

    So the compiler is warning you that you added a superfluous check, that protects you from little to nothing, because the broken code that needs to be fixed is outside your function.