我最近安裝了「klocwork」,並試圖擺脫現有代碼上的錯誤。 顯示的錯誤似乎很簡單。在char * _p_
終止時不爲空。 我已經手動添加了空終止符(儘管沒有必要),但它並不請求Klocwork。有任何想法嗎?非空終止字符串 - KlocWork錯誤,無可理解的原因
確切信息是: -
Incorrectly terminated string 'p' causes a buffer overflow in p.
char *ptr;
int writtenchars = 0 ;
va_list args;
char* destStr;
if (argc != 2) {
printf(" wrong parameters number - %d instead of %d\n", argc, 2);
char str[25]="wrong parameters number ";
char *_p_; /********************************************************/
va_start(args, str);
destStr = (char*) malloc(SNMP_BUF_LEN);
_p_= destStr;
if (destStr == NULL) {
printf("WARNING: Failed to alloc memory in in function \"snmp_rebuildstringinbuf!!!\" \n");
destStr="kukuRiko";
}
else {
writtenchars = (int) vsnprintf(destStr, 4095, str, args);
if (writtenchars>SNMP_BUF_LEN) {
printf("WARNING: Too long string rebuilded in function \"snmp_rebuildstringinbuf!!!\" %d chars\n",writtenchars);
}
destStr[writtenchars] = '\0' ; //Moshe - making sure the last value of the string is null terminated in order to prevent future buffer overflows.
}
va_end(args);
/******************************************************************************/
//The KlocWork error relates to this line //
logCWriteLog_msg(moduleId, level, __FILE__, __LINE__, _p_, ltrue);
free (_p_);
============================== ============================= 嗨,大家好, 感謝您的回答,但似乎比這更晦澀難懂。我已經將代碼細化爲這種簡單的情況: - 將代碼全部寫入一個函數時沒有錯誤,而當分配部分包含在一個函數中(以及作爲參數傳遞的文本)時,Klocwork錯誤返回。 參見此代碼: - 版本沒有一個錯誤: -
char *_p_; /*+++++++++++++++++++*/
int writtenchars = 0 ;
va_list args;
char* destStr;
char* str = "hello World";
va_start(args, str);
destStr = (char*)malloc(SNMP_BUF_LEN);
if (destStr == NULL) {
printf("WARNING: Failed to alloc memory in function \n");
}
else {
writtenchars = (int) vsnprintf(destStr, (SNMP_BUF_LEN) - 1, str, args);
}
/*+++++++++++++++++++*/
_p_ = destStr ;
if (_p_ != NULL) {
logCWriteLog_msg(moduleId, level, __FILE__, __LINE__, _p_, ltrue);
}
free (_p_);
/***********************************************************/
取代碼之間/ * ++++ * /和在函數包裹它時返回,而錯誤Klocwork的上述。
因此,
char *writingToSomeBuffer (char * str) {
int writtenchars = 0 ;
va_list args;
char* destStr;
va_start(args, str);
destStr = (char*)malloc(SNMP_BUF_LEN);
if (destStr == NULL) {
printf("WARNING: Failed to alloc memory in function \n");
}
else {
writtenchars = (int) vsnprintf(destStr, (SNMP_BUF_LEN) - 1, str, args);
}
return destStr;
}
int main() {
char *_p_;
_p_ = writingToSomeBuffer("hello world");
if (_p_ != NULL) {
logCWriteLog_msg(moduleId, level, __FILE__, __LINE__, _p_, ltrue);
}
free (_p_);
return 0 ;
}
什麼想法?
我同意你的診斷,即4096和SNMP_BUF_LEN不是明顯相關的,並且通過在任何地方使用相同的名稱(SNMP_BUF_LEN)都會改進代碼。但Klockwork也在診斷一個恰當的錯誤 - 雖然不像人們想象的那麼清楚。 – 2010-07-05 18:28:00