2010-07-13 153 views
0

Klocwork正在產生一個似乎是錯誤的警報。 它提到的bug描述了我們代碼中大約80%的錯誤。 請指教,非空結束字符串虛警?

因此就可以剪斷集(意譯): -

//a snip set 
// no bug here // 

{ 
    char*  destStr; 
    destStr = (char*)malloc(150); 
    if (destStr != NULL) { 
    destStr[0]= '\0'; //__here is the difference__ 
    char * myStr = malloc(200) ; 
    if (myStr != NULL) { 
     strcpy(myStr , destStr) ; 
    } 
    free(myStr); 
    } 
    free (destStr); 
    destStr = NULL; 
} 

//__whereas a bug here__ ! 

{ 
    char* destStr; 
    destStr = (char*) malloc(150); 
    if (destStr != NULL) { 
    destStr[0]= '\0'; // __here is the difference__ 
    } 
    else { 
    printf("hello world \n"); 
    } 
    if (destStr != NULL) { 
    char * myStr = malloc(200); 
    if (myStr != NULL) { 
     strcpy(myStr , destStr); // __NNTS (not NULL terminated string) – Buffer overflow of 'myStr' due to non null terminated string 'destStr'.__ 
    } 
    free (myStr); 
    } 
    free (destStr); 
    destStr = NULL; 
} 
//end of snip set 
+0

可能重複的[未空終止字符串 - 一個Klocwork的錯誤,沒有可理解理由](HTTP ://sackoverflow.com/questions/3181018/not-null-terminated-string-a-klocwork-error-with-no-understandable-reason) – kiamlaluno 2010-08-10 07:48:56

回答

1

您使用的是什麼版本的Klocwork產品?我只是嘗試分析提供的代碼示例,並沒有任何報告。在代碼中添加一個有意識的NPD確實會產生一個報告,只是爲了證明我實際上正在運行該工具; p建議如果您最近嘗試升級時沒有運行合理的新功能(Insight 9.1是最新發布的產品集)。

問候, 格溫費舍爾 CTO和VPř& d Klocwork的,公司 gwyn-at-klocwork.com

+0

嗨,我的版本是9.0.0(版本9.0.0.1.8),當調用strcpy時,錯誤出現在剪輯集的第二個塊中。看起來好像Klocwork不知道destStr是由前面的「if(destStr!= NULL)」終止的。當一個函數創建一個char * str並將其返回給另一個對strcpy執行類似操作的函數時,這是一個更復雜情況的解釋。 – Moshe 2010-07-14 08:32:11

+0

請注意,calloc解決了這個問題,但我不想額外的開銷,因爲經常使用原始代碼。 – Moshe 2010-07-14 08:34:09

+0

好的,建議你儘可能升級。沒有看到實際的例子,我不能保證什麼,但它是值得一試! – 2010-07-14 14:45:37

0
Please paste formatted code (read Readable code) 

起初我以爲這在本質上是obfuscated。對於這個問題,當你做一個strcpy時,你需要檢查目標字符串是否足夠容納源字符串。

這裏DEST_LEN等於分配的字節數量。

if(source != NULL && dest != NULL) 

{ 

strncpy (dest , source , DEST_LEN -1); 

} 

感謝由主持人編輯。

Klockworks將strcpy作爲錯誤檢測爲靜態分析工具。我建議你爲字符串相關的操作定義自定義宏。這將檢查要複製的內存的長度。對於其他操作,您也可以輕鬆編輯此宏並避免上述的錯誤報警。

+0

嗨,strncpy確實解決了這個問題。但是,因爲這只是對記錄器的調用的一種解釋,所以我不能確定字符串本身的大小。記錄器有: (* this)[nSeverity] << strMsg <<「:」<< destStr << LogEndl; 當destStr必須有一個空終止當然,在這種情況下,我知道它有一個 - 但Klocwork說,否則。 – Moshe 2010-07-14 08:42:49

+0

@Moshe - 請注意,當你做動態分配時,你事先知道字符串的長度。用它來分配內存,並在strncpy中。請在您的評論中更詳細地說明。 – 2010-07-14 11:46:52