简体   繁体   English

使用时间功能时出现分段错误(核心转储)错误

[英]segmentation fault (core dumped) error when using time function

Hello i am new to Linux and c programming so this might be stupid question but i couldn't find an answer. 您好,我是Linux和C编程的新手,所以这可能是愚蠢的问题,但我找不到答案。

I am writing a home work and they want me to print the execution time at the end of program using time() function, so when i used the function in my program i got the message segmentation fault (core dumped) and when i remove it the program works agine. 我正在写家庭作业,他们希望我使用time()函数在程序结束时打印执行时间,所以当我在程序中使用该函数时,出现了消息segmentation fault (core dumped)并且在删除它时该程序工作敏捷。 Then i created a test file in the code below : 然后我在下面的代码中创建了一个测试文件:

#include <stdio.h>

int main()
{
    time();
    return 0;
}

And i got the same error message. 而且我得到了相同的错误消息。

Also tried : 还尝试了:

#include <stdio.h>

int main()
{
    time(NULL);
    return 0;
}

And

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

int main()
{
    time_t t;

    time(&t);
    return 0;
}

And got the same error. 并得到了相同的错误。

so what i am doing wrong ? 所以我做错了什么?

Thanks 谢谢

In your first two examples, you forget to include time.h. 在前两个示例中,您忘记包含time.h。 That is the cause of the segmentation fault in those examples. 在这些示例中,这就是造成分段错误的原因。 If you're using gcc, try compiling with -Wall (which turns on all warnings). 如果使用的是gcc,请尝试使用-Wall进行编译(打开所有警告)。 You should get a warning indicating an implicit declaration of function "time" - in other words, that you've forgotten to include time.h. 您应该得到一个警告,指示函数“ time”的隐式声明-换句话说,您已经忘记包含time.h。

Your final example, however, works fine for me. 但是,您的最后一个示例对我来说效果很好。 If you keep getting a segmentation fault, however, try debugging with gdb. 但是,如果仍然遇到分段错误,请尝试使用gdb进行调试。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
  time_t now;
  time(&now);

  printf("%s", ctime(&now));

  return EXIT_SUCCESS;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM