gettimeofday()为什么会出现段错误
我两个程序,同样的程序流程,只不过一个是结构体变量,一个是结构体指针,但是为什么结构体指针运行完之后报错,说段错误。
正确的程序是这个:
#gettimeofday_r.c
#include <sys/time.h>#include <stdio.h>#include <unistd.h>void foo(){ int i = 0; for (; i <= 10000; i++); }int main(int argc, char *argv[]){ struct timeval start; struct timeval end; float timeuse; gettimeofday(&start, NULL); printf("start time is %d:%d\n", start.tv_sec, start.tv_usec); foo(); gettimeofday(&end, NULL); printf("end time is %d:%d\n", end.tv_sec, end.tv_usec); timeuse = 1000000 * (end.tv_sec - start.tv_sec) + ( end.tv_usec - start.tv_usec ); printf("timeuse1 is %f \n", timeuse); timeuse /= 1000000; printf("timeuse2 is %f \n", timeuse); printf("use time is %f\n", timeuse); return 0;}
start time is 1331190741:726493end time is 1331190741:726691timeuse1 is 198.000000 timeuse2 is 0.000198 use time is 0.000198
#include <sys/time.h>#include <stdio.h>#include <unistd.h>void foo(){ int i = 0; for (; i <= 10000; i++); }int main(int argc, char *argv[]){ struct timeval *start; struct timeval *end; float timeuse; gettimeofday(start, NULL); printf("start time is %d:%d\n", start->tv_sec, start->tv_usec); foo(); gettimeofday(end, NULL); printf("end time is %d:%d\n", end->tv_sec, end->tv_usec); timeuse = 1000000 * (end->tv_sec - start->tv_sec) + ( end->tv_usec - start->tv_usec ); printf("timeuse1 is %f \n", timeuse); timeuse /= 1000000; printf("timeuse2 is %f \n", timeuse); printf("use time is %f\n", timeuse); return 0;}
start time is 1331190767:111354end time is 1331190767:111558timeuse1 is 204.000000 timeuse2 is 0.000204 use time is 0.000204Segmentation fault