gpt4 book ai didi

c - 退出 main 时出现段错误

转载 作者:行者123 更新时间:2023-12-02 22:32:21 26 4
gpt4 key购买 nike

我正在编写一个非常基本的 C 程序,以尝试更好地了解时间库的工作原理并了解有关 C 的更多信息。问题是,当我在主函数结束时返回 0 时出现段错误。这是程序的文本:

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

main()
{
time_t *now;
time(now);
struct tm *tp = localtime(now);
printf("%s", asctime(tp));
return 0;
}

使用 gdb 我可以看到在第 10 行(返回 0)到目前为止一切正常,我仅有的两个变量是 now 和 tp。这是我打印它们时发生的情况:

(gdb) print now
$7 = (time_t *) 0x7fff5fbff838
(gdb) print tp
$8 = (struct tm *) 0x7fff7b13e470
(gdb) print *now
$9 = 1345338893
(gdb) print *tp
$10 = {
tm_sec = 53,
tm_min = 14,
tm_hour = 21,
tm_mday = 18,
tm_mon = 7,
tm_year = 112,
tm_wday = 6,
tm_yday = 230,
tm_isdst = 1,
tm_gmtoff = -14400,
tm_zone = 0x100802518 "EDT"
}

一切似乎都很好。但是当我点击 n 时,

Cannot access memory at address 0x50303e0d
0x0000000050303e0d in ?? ()

我不明白是什么导致了这个错误。在 main 结束时返回 0 以前从未伤害过我,而且内存地址与我正在使用的任何一个都不匹配。当我在终端中运行我的程序时,我得到了 Segmentation fault: 11。我唯一能想到的是它与操作系统有关,这有几个原因是有道理的——相对较低的内存地址,以及操作系统抛出的错误。试图访问堆栈上的内存地址以返回。但是,为什么会发生这种情况?我不太了解操作系统(我正在学习 C,所以我可以跳过类(class)要求并参加我大学提供的操作系统类(class))所以也许这是一个非常简单的问题。我尝试在同一目录中运行另一个 C 程序,一切正常。

最佳答案

你没有现在初始化,或者你可能想在堆栈上初始化它,比如

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

main()
{
time_t now;
time(&now);
struct tm *tp = localtime(&now);
printf("%s", asctime(tp));
return 0;
}

关于c - 退出 main 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023522/

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