问题
#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?
回答1:
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).
来源:https://stackoverflow.com/questions/4179345/gcc-wuninitialized-not-warning-about-uninitialized-structs