日期:2014-05-16  浏览次数:20835 次

gettimeofday()为什么会出现段错误
我两个程序,同样的程序流程,只不过一个是结构体变量,一个是结构体指针,但是为什么结构体指针运行完之后报错,说段错误。

正确的程序是这个:
#gettimeofday_r.c

C/C++ code

#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;
}


运行结果是:
C/C++ code

start time is 1331190741:726493
end time is 1331190741:726691
timeuse1 is 198.000000 
timeuse2 is 0.000198 
use time is 0.000198



错误的代码是:
#gettimeofday_w.c
C/C++ code

#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;
}



运行结果是:
C/C++ code

start time is 1331190767:111354
end time is 1331190767:111558
timeuse1 is 204.000000 
timeuse2 is 0.000204 
use time is 0.000204
Segmentation fault



错误的代码我用gdb调试,最后的程序到最后一个括号结束了,然后提示:
Cannot find bounds of current function
Program received signal SIGSEGV,segmentation fault

------解决方案--------------------
看一下函数声明就知道了,第一个参数必须是指针。
int gettimeofday(struct timeval *tv, struct timezone *tz);
------解决方案--------------------
你没有给指针分配空间啊

start=(struct timeval *)malloc(struct timeval);
gettimeofday(start, NULL);
------解决方案--------------------
函数需要一个指针,而你给了它一个未初始化的指针,程序没崩溃就算运气好了。
第一种才是标准用法,第二种需要这样:

struct timeval start;
struct timeval *pstart = &start;
gettimeofday(...);