【发布时间】:2014-07-30 23:07:39
【问题描述】:
我尝试使用
difftime(time_t end, time_t mktime(start) )
以两种不同的方式计算两个不同时间之间的差异。只是为了好奇!我发现它会导致不同的结果,失败和成功。不知道为什么会这样?
为什么会在以下两种情况下导致不同的结果?
// Failure Case 1 when execution, segmentation fault
time_t end;
time(&end);
struct tm * start; // defining a pointer
start->tm_hour = 0;
start->tm_min = 0;
start->tm_sec = 0;
start->tm_year = 114;
start->tm_mon = 6;
start->tm_mday = 29;
double second = difftime(end, mktime(start) ); // where problem come from!
// Success Case 2, with expected result
time_t end;
time(&end);
struct tm start; // defining a non-pointer
start.tm_hour = 0;
start.tm_min = 0;
start.tm_sec = 0;
start.tm_year = 114;
start.tm_mon = 6;
start.tm_mday = 29;
double second = difftime(end, mktime( &start) );
【问题讨论】:
-
您正在通过一个不确定的指针 (
struct tm *start;) 分配数据,这样做会调用 未定义的行为。 -
你忘记为 *start 分配内存
-
@TomásBadan 这种情况下如何分配内存?
-
可以使用malloc:start = malloc(sizeof(*start));
-
即便如此,由于
tm结构中的未初始化字段,您可能会得到不同的结果。例如struct tm start = {};(struct这个词在 C++ 中是可选的,在 C 中是必需的)或tm *start = new tm();[C++] 或struct tm *start = calloc(1, sizeof(tm));[C]