【问题标题】:strptime() causes EXC_BAD_ACCESSstrptime() 导致 EXC_BAD_ACCESS
【发布时间】:2017-07-11 21:54:23
【问题描述】:

我正在尝试使用 strptime() 函数将字符串解析为 tm 结构。

int main(int argc, const char * argv[]) {
    char raw_date1[100];
    char date1[100];
    struct tm *timedata1 = 0;

    printf("please provide the first date:");
    fgets(raw_date1, sizeof(raw_date1), stdin);

    strip_newline(date1, raw_date1, sizeof(raw_date1));

    char format1[50] = "%d-%m-%Y";

    strptime(date1, format1, timedata1);

在最后一行,程序崩溃并显示以下消息:EXC_BAD_ACCESS (code=1, address=0x20)

为什么?

一些额外信息:根据调试器,在崩溃时,date123/23/2323format1"%d-%m-%Y"timedata1NULL

【问题讨论】:

  • 试试struct tm timedata1;..strptime(date1, format1, &timedata1);
  • 成功了。不过,我不明白为什么。对我来说,timedata1 如果声明为 struct tm *timedata;&timedata1 如果 timedata1 声明为 struct tm timedata; 相同。
  • strptime() 函数想要写入您应该传递给它的 struct tm。你传递了一个空指针;它很沮丧。
  • struct tm *timedata1 = 0; 定义了一个指针,并将其初始化为 0,即 NULL。取消引用 NULL 指针会导致异常。
  • 好的。即使我没有初始化 timedata1 并且只声明它,为什么问题仍然存在? (请参阅我在 Stephan Lechner 的回答下的问题)

标签: c date time strptime


【解决方案1】:

在您的代码中:

struct tm *timedata1 = 0;

一样
struct tm *timedata1 = NULL;

因此,声明

strptime(date1, format1, timedata1);

一样
strptime(date1, format1, NULL);

即,在您的代码中,您将NULL 作为参数传递给strptime,这将取消对指针的引用并产生未定义的行为/错误的访问。

所以你应该写如下内容:

struct tm timedata1 = {0};
strptime(date1, format1, &timedata1);

【讨论】:

  • 所以解决方法是……?
  • @Jonathan Leffler:OP 没有要求修复 :-) ;不 - 我只是看看是否需要初始化。
  • 知道了,谢谢。但是,即使我写了struct tm *timedata1(没有0),同样的问题仍然存在。我只是想知道,为什么会这样?因为我认为type *var; var;type var; &var; 是等价的。
  • 不,它们不等同。 type *var; 为指针值保留内存,该指针值保持未初始化并“指向某处”(实际上取消引用它是未定义的行为,可能是错误的访问)。相比之下,type var;type 类型的值保留内存,而&var 则提供此(有效)内存的地址。
【解决方案2】:

您将一个空指针传递给strptime() 作为目标tm 结构。这具有未定义的行为。您应该将指针传递给定义为局部变量的tm 结构:

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

int main(int argc, const char *argv[]) {
    char raw_date1[100];
    char date1[100];
    struct tm timedata1;

    printf("please provide the first date:");
    if (fgets(raw_date1, sizeof(raw_date1), stdin)) {
        strip_newline(date1, raw_date1, sizeof(raw_date1));

        char format1[50] = "%d-%m-%Y";

        strptime(date1, format1, &timedata1);

        ...
    }
    return 0;
}

请注意,strptime 不是标准 C 函数,尽管它作为 POSIX-1.2001 的一部分广泛使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 2016-11-19
    • 2012-10-02
    • 2011-04-14
    • 2017-03-15
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多