GCC -Wuninitialized 不警告未初始化的结构

发布于 2024-10-02 23:29:16 字数 476 浏览 7 评论 0原文

#include <ctime>
#include <iostream>
#include <cstring>
int main()
{

struct tm tm ;
//memset(&tm, 0, sizeof(struct tm));
strptime("1 Jan 2000 13:00:00", "%d %b %Y %H:%M:%S", &tm);
time_t t =mktime(&tm);
std::cout << ctime(&t);
return 0;
}

g++ -Wuninitialized -O2 test.cpp 不会警告 tm 尚未初始化。 Valgrind 会一直这样做,直到添加 memset 行。 Linux 上 strptime 的手册页说它应该被初始化,并且在我初始化它之前,我在一个更复杂的程序上看到了随机日期。在这些情况下是否有任何 GCC 标志会产生警告?

#include <ctime>
#include <iostream>
#include <cstring>
int main()
{

struct tm tm ;
//memset(&tm, 0, sizeof(struct tm));
strptime("1 Jan 2000 13:00:00", "%d %b %Y %H:%M:%S", &tm);
time_t t =mktime(&tm);
std::cout << ctime(&t);
return 0;
}

g++ -Wuninitialized -O2 test.cpp doesn't warn about tm not having been initialized. Valgrind does until the memset line is added. the Man pages for strptime on Linux say it should be initialised and I was seeing randomized dates on a more complicated program until I did initialise it. Are there any GCC flags that will produce a warning in these circumstances?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自演自醉 2024-10-09 23:29:17

GCC 无法在编译时查看 strptimemktimectime 函数已编译的代码。您只需从调用点传递结构的地址,而不读取任何内容。另一方面,Valgrind 执行您的程序并跟踪所有内存,并检查在写入特定内存块之前是否存在读取,从而可以告诉您。

如果这些函数在标头中内联定义,则编译器可能有机会内联它们并将指针地址追溯到未初始化的结构。不过,我还没有测试过 GCC 在这方面有多好(或者就这一点而言,一般的编译器)。

GCC can't look into the already compiled code of the strptime, mktime and ctime functions at compile time. You just pass the address of the struct, from the point of the call, without reading anything. Valgrind on the other hand executes your program and tracks all the memory and will check up whether there is a read before a write of a particular memory block and can thus tell you.

If those functions would be defined inline in the header, you could have a chance that the compiler could inline them and track back the pointer address back to the uninitialized struct. I haven't tested how good GCC is at that, though (or for that matter, compilers in general).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文