2012-02-28 82 views
0

我有一個循環檢查文件的修改時間來執行它的I/O。 我正在使用stat命令。 Valgrind拋出未初始化字節的錯誤消息..只是出了什麼問題?我已經確保文件名列表不爲空,並且在將它們作爲參數傳遞給它之前存在這些文件,但錯誤仍然存​​在。c linux stat param指向未初始化的字節?

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== 

Decleration

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); 
+0

只是因爲在'fileNameList進入[我]'不爲空呢並不意味着它被初始化。例如,'char * fileNameList [10];'將包含(隨機)非空指針,因爲它們尚未初始化。你能說明'fileNameList'是如何聲明和填充的嗎? – hmjd 2012-02-28 11:31:09

+0

如果我在文件名列表的循環開始處執行printf,則會檢出值。 – 2012-02-28 11:34:53

+0

你能發表更多的代碼嗎? 'fileNameList'的聲明和填充以及'fcount'的賦值? – hmjd 2012-02-28 11:38:29

回答

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 } }; 
+0

非常感謝hmjd幫助。 – 2012-02-28 12:06:44

1

的文件名如果沒有初始化數組filename首先,它的內容不會是零,而是別的東西(很多時候它是0xCC,但它可能在不同的系統/拱形等上有所不同)。

+0

我不明白。首先填充文件名稱數組,然後將文件名傳遞給stat命令。你是說我甚至在用名字初始化之前必須初始化爲零?錯誤是在運行時 – 2012-02-28 11:32:03

+0

不,如果你已經填充它,沒關係。也許有一些你沒有給它賦值的單元格? – MByD 2012-02-28 11:32:47