gettimeofday()为什么会出现段错误

__阿飞__ 2012-03-08 03:12:59
我两个程序,同样的程序流程,只不过一个是结构体变量,一个是结构体指针,但是为什么结构体指针运行完之后报错,说段错误。

正确的程序是这个:
#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:726493
end time is 1331190741:726691
timeuse1 is 198.000000
timeuse2 is 0.000198
use time is 0.000198


错误的代码是:
#gettimeofday_w.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 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
...全文
529 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
__阿飞__ 2012-03-08
  • 打赏
  • 举报
回复
ok,谢谢这位大哥,回答正确啦,谢谢你,分都给你喽,多谢指教!
[Quote=引用 2 楼 justkk 的回复:]

你没有给指针分配空间啊

start=(struct timeval *)malloc(struct timeval);
gettimeofday(start, NULL);
[/Quote]
youngwolf 2012-03-08
  • 打赏
  • 举报
回复
函数需要一个指针,而你给了它一个未初始化的指针,程序没崩溃就算运气好了。
第一种才是标准用法,第二种需要这样:

struct timeval start;
struct timeval *pstart = &start;
gettimeofday(...);
justkk 2012-03-08
  • 打赏
  • 举报
回复
你没有给指针分配空间啊

start=(struct timeval *)malloc(struct timeval);
gettimeofday(start, NULL);
gohome520 2012-03-08
  • 打赏
  • 举报
回复
看一下函数声明就知道了,第一个参数必须是指针。
int gettimeofday(struct timeval *tv, struct timezone *tz);

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧