Sunday, February 27, 2022

[靜態檢查工具] cppcheck

Cppcheck是一種用於C和C ++ 程式語言的靜態代碼分析工具。 它是一個多功能工具,可以檢查非標準代碼


首先必須安裝cppcheck

sudo apt-get install cppcheck

cppcheck xxx.c --enable=all

cppcheck -DA xxx.c --enable=all

變數宣告

1
2
3
4
5
6
7
8
int a;
int b;
int c = 1;
int d = 2;

b++;
c++;
d = 4;

(style) Variable 'd' is reassigned a value before the old one has been used.

(style) Unused variable: a

(style) Variable 'b' is not assigned a value.

(style) Variable 'd' is assigned a value that is never used.

(error) Uninitialized variable: b

記憶體管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int *ptra;
int *ptrb;
int *ptrc;
int *ptrd = NULL;

ptra = (int*)malloc(100);
ptrb = (int*)malloc(100);

if (NULL == ptra) {
return *ptrd;
}

*(ptrc + 1) = 5;

free(ptrb);

*(ptrb + 2) = 6;

(error) Null pointer dereference: ptrd

(style) Variable 'ptrc' is not assigned a value.

(error) Memory leak: ptrb (error) Memory leak: ptra

(error) Dereferencing 'ptrb' after it is deallocated / released

(error) Null pointer dereference

(error) Uninitialized variable: ptrc

Buffer邊界

1
2
3
4
5
int i;
int a[10];

for (i = 0; i <= 10; i++)
a[i] = i;

(error) Array 'a[10]' accessed at index 10, which is out of bounds.

目前市面上的靜態程式檢查工具眾多,例如splint, coverity, cppcheck等等,每個工具都有其擅長的部分
就使用過splint和cppcheck的經驗來看例如對於不需要使用或不需要給初始值的狀況cppcheck > splint,但對於buffer overwrite的檢查splint > cppchek,因此若想讓程式更加完善,可以使用多些檢查工具達成目標

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能