【问题标题】:c linux stat param points to uninitialised bytes?c linux stat参数指向未初始化的字节?
【发布时间】:2012-03-17 20:52:08
【问题描述】:

我有一个循环检查文件的修改时间以对其执行 i/o。 我正在使用 stat 命令。 Valgrind 抛出未初始化字节的错误消息 .. 出了什么问题?我确保文件名列表不为空,并且文件在将它们作为参数传递给它之前存在,但错误仍然存​​在。

for (i = 0; i < fcount; i++) {
    if (modTimeList[i] == 0) {
        int statret = 0;
        if(fileNameList[i]!=NULL)
        statret = stat(fileNameList[i], &file_stat);  // error 
        if (statret == -1) {
            printf(" stat error at %d", i);
        } else {
            modTimeList[i] = file_stat.st_mtime;
            // process
        }
    } else {
        int statret2 = 0;
        if(fileNameList[i]!=NULL)
        statret2 = stat(fileNameList[i], &file_stat); // error
        if (statret2 == -1) {
            printf(" stat error at %d", i);
        } else {
            if (modTimeList[i] < file_stat.st_mtime) {
                // process
            }
        }

    }

}

错误信息

==5153== Syscall param stat64(file_name) points to uninitialised byte(s)
==5153==    at 0x40007F2: ??? (in /lib/ld-2.7.so)
==5153==    by 0x804992B: stat (in /home/)
==5153==    by 0x8049559: checkForFiles (in /home)
==5153==    by 0x804983F: main (in /home)
==5153==  Address 0xbe9271d0 is on thread 1's stack
==5153==  Uninitialised value was created by a stack allocation
==5153==    at 0x804924C: checkForFiles (in /home/)
==5153==

声明

char fileNameList[100][256];

我正在像这样初始化文件名​​

sprintf(inputPath, "find -name %s*.ext", filename);
        fpop = popen(inputPath, "r");
        while (fgets(inputPath, sizeof(inputPath) - 1, fpop) != NULL) {
            strcpy(fileNameList[fcount], trimwhitespace(inputPath));
            fcount++;
        }
        pclose(fpop);

【问题讨论】:

  • fileNameList[i] 处的条目不为 NULL 并不意味着它已被初始化。例如,char* fileNameList[10]; 将包含(随机)非空指针,因为它们尚未初始化。你能说明fileNameList 是如何声明和填充的吗?
  • 如果我在 filenamelist 的循环开始处执行 printf ,则值会检出。
  • 你能发布更多代码吗? fileNameList 的声明和人口加上fcount 的分配?

标签: c linux error-handling valgrind stat


【解决方案1】:

如果您没有先初始化 filename 数组,则其内容不会为零,而是其他内容(很多时候是 0xCC,但在不同的系统/拱门/等上可能会有所不同)。

【讨论】:

  • 我不明白。首先填充文件名数组,然后将文件名传递给 stat 命令。您是说我必须在使用名称初始化它们之前将其初始化为零吗?错误在运行时
  • 不,如果你已经填好了,没关系。也许有些单元格没有赋值?
【解决方案2】:

fileNameList 声明为:

char fileNameList[100][256];

if (fileNameList[i] != NULL) 将始终为真,因为fileNameList[i] 不是空指针。您应该将检查更改为:

if ('\0' != *fileNameList[i]) /* Check if empty string. */

但是,为了让它工作,你需要初始化fileNameList:

char fileNameList[100][256] = { { 0 } };

【讨论】:

  • 感谢 hmjd 非常有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 2016-03-12
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多