gpt4 book ai didi

c++ - 是什么导致此 C 代码中出现段错误?

转载 作者:太空狗 更新时间:2023-10-29 20:32:21 27 4
gpt4 key购买 nike

编辑:感谢到目前为止的回答,至少我现在可以编译它,但我仍然遇到段错误。

对于编译,我使用以下行:

gcc -g -O0 -I../include -L../ test.c -static -lrt

源码如下:

#include <sys/time.h>
#include <time.h>
#include <stdio.h>


struct timespec *diff(struct timespec *start, struct timespec *end);

int main()
{
struct timespec time1, time2;
int i;
int temp = 0;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
for (i = 0; i< 242000000; i++)
temp+=temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
printf("sec: %d, nsec: %f",diff(&time1,&time2)->tv_sec, diff(&time1,&time2)->tv_nsec);
//cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
return 0;
}

struct timespec *diff(struct timespec *start, struct timespec *end)
{
struct timespec *temp;
if ((end->tv_nsec-start->tv_nsec)<0) {
temp->tv_sec = end->tv_sec-start->tv_sec-1;
temp->tv_nsec = 1000000000+end->tv_nsec-start->tv_nsec;
} else {
temp->tv_sec = end->tv_sec-start->tv_sec;
temp->tv_nsec = end->tv_nsec-start->tv_nsec;
}
return temp;
}

我现在收到以下警告:

test.c: In function ‘main’:
test.c:17: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘__time_t’
test.c:17: warning: format ‘%f’ expects type ‘double’, but argument 3 has type ‘long int’

段错误肯定是由我对结构的处理引起的。很久以前,我最后一次不得不与 C 打交道......

非常感谢,马库斯

最佳答案

您的 diff 函数的签名是 timespec diff(timespec start, timespec end),它应该是 struct timespec diff(struct timespec start, struct timespec end)


编辑您的 diff 函数正在分配给一个未初始化的结构指针,您可能希望将其更改为如下所示。

void diff(struct timespec *start, struct timespec *end,
struct timespec *result);

int main()
{
struct timespec time1, time2, result;
int i;
int temp = 0;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
for (i = 0; i< 242000000; i++)
temp+=temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);

diff(&time1, &time2, &result);

printf("sec: %ld, nsec: %ld", (long int)result.tv_sec,
(long int)result.tv_nsec);
return 0;
}

void diff(struct timespec *start, struct timespec *end,
struct timespec * result)
{
if ((end->tv_nsec-start->tv_nsec)<0) {
result->tv_sec = end->tv_sec-start->tv_sec-1;
result->tv_nsec = 1000000000+end->tv_nsec-start->tv_nsec;
} else {
result->tv_sec = end->tv_sec-start->tv_sec;
result->tv_nsec = end->tv_nsec-start->tv_nsec;
}
}

关于c++ - 是什么导致此 C 代码中出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2147834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com