You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sleep函数使用后内存异常:结构体时间字段均显示最后值问题排查

问题原因与解决方法

问题原因

核心问题出在get_current_time函数里的static char time_string[9]:

  • static修饰的变量生命周期贯穿整个程序运行期,且只会被初始化一次。
  • 每次调用get_current_time时,都会覆盖同一块内存里的时间字符串,然后返回指向这块内存的指针。
  • 所有cusDetails结构体的cusTime字段都指向同一个内存地址,最后遍历数组时,这块内存里的内容是最后一次调用函数时写入的时间,因此所有条目显示的都是最后一个时间。

解决方法

以下是三种可行的修复方案:

方案1:结构体改用字符数组存储时间

直接在结构体里定义固定大小的字符数组,替代指针,让每个结构体拥有独立的时间存储空间:

typedef struct cusDetails
{
    int cusId;
    char cusAct;
    char cusTime[9]; // 刚好容纳HH:MM:SS格式字符串+结束符
}cusDetails;

赋值时用strcpy复制时间字符串:

// 替换原代码中customers[i].cusTime = get_current_time();
strcpy(customers[i].cusTime, get_current_time());

方案2:动态分配内存存储时间

保持结构体的指针字段不变,但每次获取时间后手动分配内存复制字符串:

// 替换原代码中customers[i].cusTime = get_current_time();
char *temp_time = get_current_time();
customers[i].cusTime = malloc(strlen(temp_time) + 1);
strcpy(customers[i].cusTime, temp_time);

注意:使用完后要释放内存避免泄漏,在程序末尾添加:

for (i = 0; i < numCus; i++)
{
    free(customers[i].cusTime);
}
free(customers);

方案3:修改时间函数,由调用者提供缓冲区

去掉get_current_time里的static数组,改为让调用者传入缓冲区:

// 修改后的getTime.h中的函数
void get_current_time(char* time_string, size_t buf_size){
    time_t current_time;
    struct tm* time_info;

    current_time = time(NULL);
    time_info = localtime(&current_time);
    strftime(time_string, buf_size, "%H:%M:%S", time_info);
}

主程序调用时,传入结构体的字符数组(需先修改结构体为方案1的形式):

get_current_time(customers[i].cusTime, sizeof(customers[i].cusTime));

内容的提问来源于stack exchange,提问作者Martin Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:53:24