c++ - 警告 : null destination pointer [-Wformat-overflow=] with GCC 11. 2.1

标签 c++ gcc-warning sanitizer

这是我的代码:

#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 ;
}

使用 GCC 11.2.1,使用以下命令:

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

我得到:

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

我无法理解警告的原因。我做错什么了吗?

最佳答案

这似乎是来自 g++ 编译器的错误/误报警告。该消息试图警告您使用指针变量作为 sprintf 的目标。如果该指针为空(或指向大小不足的缓冲区),函数可能会失败。

抑制此警告是“微不足道的”:只需添加一个检查 str调用 sprintf 之前不为空:

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

但是,您的代码就其本身而言没有问题,并且该检查完全是多余的,因为标准运算符 new [] ,正如您所使用的那样,无法返回空指针。您正在使用new的“版本(2)”如 this cppreference page 中所述。请注意,来自同一页面:

Return value

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

如果您的new char[64]表达式无法分配足够的内存,那么将抛出异常并且(如您的代码所示)sprintf函数将不会被调用。

关于c++ - 警告 : null destination pointer [-Wformat-overflow=] with GCC 11. 2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73009176/

相关文章:

c++ - C++ FakeIt 库多重继承

c++ - 是否有用于 SQLCipher 的 ODBC 驱动程序?

c++ - lower_bound(v.begin(), v.end(), x)

c++ - 访问外部窗口句柄

gcc - 如何在 C 中类型转换文字

c++ - 使用 Clang 的 UB sanitizer 构建的程序的附加输出

c - 如何消除 Linux 中 DDA 行算法中的以下错误?

gcc - 浮点异常在新的 gfortran 版本中发出信号

c++ - std::vector<std::vector<int>> push_back 给出堆缓冲区溢出

fortran - 是否允许为另一个过程的可选参数传递一个不存在的假定形状数组?