歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Ubuntu系統下C語言代碼檢查工具-- Splint

Ubuntu系統下C語言代碼檢查工具-- Splint

日期:2017/3/2 16:41:53   编辑:Linux服務器

看一下下面的代碼(當然包括錯誤,以檢驗splint的功能):

#include
int main(int argc,char* argv[]){
int a=100; /*沒有使用的變量*/
int b[8];
printf("Hello c\n");
b[9]=100; /*明顯數組越界 */
/* 用到了兩個為聲明的變量c和d/
c=100;
d=10;
return 0;
}

現在可以用splint來檢查一下,為了檢驗是否可以檢測到數組越界,使用+bounds選項。

splint hi.c +bounds

輸出結果:

hi.c: (in function main)
hi.c:9:2: Unrecognized identifier: c
Identifier used in code has not been declared. (Use -unrecog to inhibit
warning)
hi.c:10:2: Unrecognized identifier: d
hi.c:4:6: Variable a declared but not used
A variable is declared but never used. Use /*@unused@*/ in front of
declaration to suppress message. (Use -varuse to inhibit warning)
hi.c:7:2: Likely out-of-bounds store:
b[9]
Unable to resolve constraint:
requires 7 >= 9
needed to satisfy precondition:
requires maxSet(b @ hi.c:7:2) >= 9
A memory write may write to an address beyond the allocated buffer. (Use
-likely-boundswrite to inhibit warning)
hi.c:3:14: Parameter argc not used
A function parameter is not used in the body of the function. If the argument
is needed for type compatibility or future plans, use /*@unused@*/ in the
argument declaration. (Use -paramuse to inhibit warning)
hi.c:3:25: Parameter argv not used
Finished checking --- 6 code warnings

現在詳細看一下結果:

檢查結果1:

hi.c:9:2: Unrecognized identifier: c
Identifier used in code has not been declared. (Use -unrecog to inhibit
warning)
hi.c:10:2: Unrecognized identifier: d
hi.c:4:6: Variable a declared but not used
A variable is declared but never used. Use /*@unused@*/ in front of
declaration to suppress message. (Use -varuse to inhibit warning)

這些應該是splint檢測到變量c和d沒有聲明。

檢查結果2:

hi.c:7:2: Likely out-of-bounds store:
b[9]
Unable to resolve constraint:
requires 7 >= 9
needed to satisfy precondition:
requires maxSet(b @ hi.c:7:2) >= 9
A memory write may write to an address beyond the allocated buffer. (Use
-likely-boundswrite to inhibit warning)

這些是檢查存在數組越界,因為吧b[8]的最大數組序號應該是7,而不是9,所以出現requires 7 >= 9;

檢查結果3:

hi.c:3:14: Parameter argc not used
A function parameter is not used in the body of the function. If the argument
is needed for type compatibility or future plans, use /*@unused@*/ in the
argument declaration. (Use -paramuse to inhibit warning)
hi.c:3:25: Parameter argv not used

這些表明argc和argv變量聲明了,但是沒有使用。這個不是什麼問題。

如果小心使用splint,應該對於c語言的程序編寫有非常大的輔助作用!

Copyright © Linux教程網 All Rights Reserved