c - Valgrind 读取大小无效

标签 c gcc memory c99

首先,我浏览了其他类似的问题,但它们对我没有帮助。我有以下 Valgrind 输出:

我的代码:

int f_gozlemZamaniFarki(long long t1,long long t2)
{
    char *time1 = (char*)calloc(12,sizeof(char));
    char *time2 = (char*)calloc(12,sizeof(char));

    *time1 = '\0';
    *time2 = '\0';

    sprintf(time1,"%lli",t1);
    sprintf(time2,"%lli",t2);

    int year,month,day,hour,minute,timeDif;
    int status = 0;

    struct tm tm1;
    struct tm tm2;

    time_t timeF = NULL;
    time_t timeS = NULL;

    if(sscanf(time1,"%4d%2d%2d%2d%2d",&year,&month,&day,&hour,&minute) != EOF)
    {
        tm1.tm_year = year - 1900;
        tm1.tm_mon = month;
        tm1.tm_mdmonth = day;
        tm1.tm_hour = hour;
        tm1.tm_min = minute;
        tm1.tm_sec = 0;
        timeF = mktime(&tm1);
    }

    if(sscanf(time2,"%4d%2d%2d%2d%2d",&year,&month,&day,&hour,&minute) != EOF)
    {
        tm2.tm_year = year - 1900;
        tm2.tm_mon = month;
        tm2.tm_mdmonth = day;
        tm2.tm_hour = hour;
        tm2.tm_min = minute;
        tm2.tm_sec = 0;
        timeS = mktime(&tm2);
    }

    timeDif = (timeF - timeS) / 60;

    if ((timeDif < 0) || (timeDif > 59))
    {
        status = 1;
    }

    free(time1);
    free(time2);

    return status;
}

valnggrid输出

==12726== Invalid read of size 1
==12726==  Address 0x1786dccc is 0 bytes after a block of size 12 alloc'd
==12726==    at 0x4C2AE45: calloc (vg_replace_malloc.c:711)
==12726==    by 0x405171: f_gozlemZamaniFarki (in /home/aws/bin/awsdDataWriter)
==12726== Conditional jump or move depends on uninitialised value(s)
==12726==  Uninitialised value was created by a stack allocation
==12726==    at 0x405150: f_gozlemZamaniFarki (in /home/aws/bin/awsdDataWriter)

我的所有变量都已初始化(我希望),所以我不明白为什么 Valgrind 对我大喊大叫。 您对使代码正确并犯错误有什么建议吗?

最佳答案

我更改了这些行,解决了我的问题。

char *time1 = (char*)calloc(13,sizeof(char));
char *time1 = (char*)calloc(13,sizeof(char));

//*time1 = '\0';
//*time2 = '\0';

关于c - Valgrind 读取大小无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40806368/

相关文章:

c - 为链表节点中的字符串动态分配内存

gcc 忽略 LC_ALL

Python-Ptrace - PtraceProcess.cont() 之后会发生什么?

c++ - 正确删除EGL Opengles 2.0

c - Pthread 互斥锁

c - 我无法弄清楚我的指针错误

c - Kernighan & Ritchie 代码示例混淆

macos - 没有multilib的gcc是什么意思?

c - 如何在具有头文件的gcc中编译C程序?

linux - meminfo 中的 DirectMapXX 字段表示什么?