Redian新闻
>
[转载] 活见鬼了---搞不定的程序
avatar
[转载] 活见鬼了---搞不定的程序# Unix - 噫吁兮,危乎高哉
r*y
1
【 以下文字转载自 Programming 讨论区 】
【 原文由 rossby 所发表 】
我写了个程序,两个,几乎一模一样,但是一个在UNIX下给出正确
结果另外一个segmentation fault . 到Linux 下一试,还是一样.晕了.
给出正确结果的程序
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "sys/time.h"
void main (int argc, char *argv)
{
int i, j;
struct timeval *tp;
struct timezone *tz=NULL;
i = gettimeofday(tp, tz);
printf("flag %d\n ", i);
printf("time %ld\n", tp->tv_sec);
printf("time %ld\n", tp->tv_usec);
}
segmentation fault的程
#include "stdio.h"
#include "stdlib.h"
#i
avatar
n*d
2
tp不应当是指针,换成结构吧

【在 r****y 的大作中提到】
: 【 以下文字转载自 Programming 讨论区 】
: 【 原文由 rossby 所发表 】
: 我写了个程序,两个,几乎一模一样,但是一个在UNIX下给出正确
: 结果另外一个segmentation fault . 到Linux 下一试,还是一样.晕了.
: 给出正确结果的程序
: #include "stdio.h"
: #include "stdlib.h"
: #include "math.h"
: #include "sys/time.h"
: void main (int argc, char *argv)

avatar
l*y
3

呵呵, 你犯了个典型的不懂指针概念的错误。
man gettimeofday , 你会看到
"int gettimeofday(struct timeval *tp, void *);"
"If tp is a null pointer, the current time information is not
returned or set."
而你在后面使用了 tp->*****
作为一个指针,怎么可以不开一块内存就使用呢?
这样使用指针其后果是不可预测的, 第一个程序
没出错并不意味着它就对。 两个都是错的。

看看 timeval结构的大小,照样分块内存给tp就没事了.
不想查的话,就往大了给,反正不用也是给猪吃了。



【在 r****y 的大作中提到】
: 【 以下文字转载自 Programming 讨论区 】
: 【 原文由 rossby 所发表 】
: 我写了个程序,两个,几乎一模一样,但是一个在UNIX下给出正确
: 结果另外一个segmentation fault . 到Linux 下一试,还是一样.晕了.
: 给出正确结果的程序
: #include "stdio.h"
: #include "stdlib.h"
: #include "math.h"
: #include "sys/time.h"
: void main (int argc, char *argv)

avatar
a*n
4

It seems that what you said is not correct.
tp of course should be ptr to struct timeval.
What you need to do is to allocate memory for *tp,
so after struct timeval *tp ;
add
tp=(struct timeval*)malloc(1);

【在 n******d 的大作中提到】
: tp不应当是指针,换成结构吧
avatar
w*g
5
其实都对,只有分配一块内存给tp就可以了。即可以从heap中
分配(用malloc),也可以从栈上分配(换成结构):
struct timeval t;
struct timeval* tp = &t;
那个程序的问题在于tp没有初始化。

【在 a**n 的大作中提到】
:
: It seems that what you said is not correct.
: tp of course should be ptr to struct timeval.
: What you need to do is to allocate memory for *tp,
: so after struct timeval *tp ;
: add
: tp=(struct timeval*)malloc(1);

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。