strptime() 导致 EXC_BAD_ACCESS
strptime() causes EXC_BAD_ACCESS
我正在尝试使用 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)
。
为什么?
一些额外信息:根据调试器,在崩溃时,date1
是 23/23/2323
,format1
是 "%d-%m-%Y"
和 timedata1
是 NULL
.
在您的代码中:
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);
您正在将空指针作为目标 tm
结构传递给 strptime()
。这具有未定义的行为。您应该将指针传递给定义为局部变量的 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 的一部分被广泛使用。
我正在尝试使用 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)
。
为什么?
一些额外信息:根据调试器,在崩溃时,date1
是 23/23/2323
,format1
是 "%d-%m-%Y"
和 timedata1
是 NULL
.
在您的代码中:
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);
您正在将空指针作为目标 tm
结构传递给 strptime()
。这具有未定义的行为。您应该将指针传递给定义为局部变量的 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 的一部分被广泛使用。