这是我的代码:
#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/