c++gcc-warningsanitizer

Warning: null destination pointer [-Wformat-overflow=] with GCC 11.2.1


Here is my code:

#include <iostream>
#include <cstdio>

int main()
{
    char *str = new char[64] ;
    std::sprintf(str, "msg: %s", "hello world") ;

    std::cout << str << std::endl ;
    delete [] str ;

    return 0 ;
}

With GCC 11.2.1, using the following command:

g++ -O -fsanitize=undefined -Wformat-overflow test.cpp

I get:

test.cpp:7:17: warning: null destination pointer [-Wformat-overflow=]
    7 |     std::sprintf(str, "msg: %s", "hello world") ;
      |     ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I failed to understand the reason for the warning. Did I do anything wrong?


Solution

  • This seems like a bug/false-positive warning from the g++ compiler. The message is trying to warn you that using a pointer variable as the destination for the sprintf function could fail if that pointer is null (or points to a buffer of insufficient size).

    It is 'trivial' to suppress this warning: simply add a check that str is not null before calling sprintf:

    if (str) std::sprintf(str, "msg: %s", "hello world");
    

    However, your code is fine as it stands, and that check is entirely superfluous, because the standard operator new [], as you have used it, cannot return a null pointer. You are using "Version (2)" of new as described on this cppreference page. Note, from that same page:

    Return value

    1-4) non-null pointer to suitably aligned memory of size at least size

    If your new char[64] expression fails to allocate sufficient memory, then an exception will be thrown and (as your code stands) the sprintf function will not be called.