GCC -Wuninitialized 不警告未初始化的结构
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GCC 无法在编译时查看
strptime
、mktime
和ctime
函数已编译的代码。您只需从调用点传递结构的地址,而不读取任何内容。另一方面,Valgrind 执行您的程序并跟踪所有内存,并检查在写入特定内存块之前是否存在读取,从而可以告诉您。如果这些函数在标头中内联定义,则编译器可能有机会内联它们并将指针地址追溯到未初始化的结构。不过,我还没有测试过 GCC 在这方面有多好(或者就这一点而言,一般的编译器)。
GCC can't look into the already compiled code of the
strptime
,mktime
andctime
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).