c - time_t 和 char* 变量意外被覆盖

标签 c linux time ctime time-t

下面的代码

{
    time_t t;
    t = time(NULL);
    char *A;
    A = ctime(&t);
    printf("%s -\n", A);
    sleep(2);
    time_t t1;
    t1 = time(NULL);
    printf("%s HERE A =\n", A);
    char *B = ctime(&t1);
    printf("%s HERE B =\n", B);
    printf("%s\n", B);
}

有输出

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:35 2019
 HERE B =
Sat Mar 30 19:10:35 2019

那么变量 A 是如何改变的呢?我应该怎么做才能使 A 保持固定值

char *A; 更改为 const char *A; 没有帮助

预期

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:33 2019
 HERE B =
Sat Mar 30 19:10:35 2019

最佳答案

因此,ctime 返回一个指向字符串的指针。您将该指针分配给 A 和 B。在这种情况下,它返回相同的指针,这意味着 A 和 B 指向内存中的相同地址。如果您添加代码来打印地址,您可以看到这一点:

printf("A=0x%x, B=0x%x", A, B);

time 的手册页解释说这是需要注意的行为:

The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The function also sets the external variables tzname, timezone, and daylight (see tzset(3)) with information about the current timezone. The reentrant version ctime_r() does the same, but stores the string in a user-supplied buffer which should have room for at least 26 bytes. It need not set tzname, timezone, and daylight.

因此,要解决此问题,您可以使用 ctime 的可重入版本,ctime_r:

char C[27];
ctime_r(&t1, &C);

您还可以使用 strcpystrdup 将其复制到您自己的不会被覆盖的字符串中。

这是解决该问题的另一个答案:Saving new points in time with ctime overwrites the old strings?

关于c - time_t 和 char* 变量意外被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432073/

相关文章:

MySQL 数据以 10 分钟为间隔计数

c - 检索 list_head 对象的父结构

c++ - 独立程序的多对一双向通信

linux - openSuse中的`dotnet new command`导致`No usable version of the libssl was found`错误

Java 8 DateTime API 在模式和值都未知时解析日期字符串

go - 如何不舍入持续时间

c - 交换两个字符

c++ - 几乎均等地拆分 float 而没有损失

c - C中的双向链表快速排序

objective-c - 使用 Xcode 项目 Objective C 加载 C 共享库