我正在测试是否可以使用gettimeofday()来测量一段代码的性能。
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval *tp_begin;
gettimeofday(tp_begin, NULL);
if (tp_begin == NULL) printf("tp_begin: Strange...\n");
struct timeval *tp_end;
gettimeofday(tp_end, NULL);
if (tp_end == NULL) printf("tp_end: Strange...\n");
return 0;
}这段代码进行了编译(使用gcc -g test.c -o test),我希望stdout不会输出任何内容,但输出如下:
tp_end: Strange...我已经多次尝试运行它,但结果总是相同的。这里发生了什么事?
发布于 2019-05-26 10:35:38
您正在向函数传递一个未初始化的指针。结果可能是任何东西,它是未定义的行为。
要从gettimeofday获得结果,您需要传递一个指向缓冲区的有效指针,函数将填充该缓冲区。该函数不提供缓冲区(即使它想也不能提供缓冲区,因为指针参数是通过值传递的)。
https://stackoverflow.com/questions/56310197
复制相似问题