splint的安装与使用

简介

splint是一个GNU免费授权的 Lint程序,是一个动态检查C语言程序安全弱点和编写错误的程序。Splint会进行多种常规检查,包括未使用的变量,类型不一致,使用未定义变量,无法执行的代码,忽略返回值,执行路径未返回,无限循环等错误。

安装

下载源代码,按照安装步骤安装splint。

 

make的时候出现下列错误:

cscanner.o: In function `input':
/home/pngynghay/splint/src/cscanner.c:2483: undefined reference to `yywrap'
cscanner.o: In function `yylex':
/home/pngynghay/splint/src/cscanner.c:2133: undefined reference to `yywrap'
collect2: ld returned 1 exit status
make[2]: *** [splint] Error 1

修改文件cscanner.c,在其中添加函数实现
int yywrap()
{
        return 1;
}
重新make即可。


配置

添加环境变量:
vim ~/.bashrc
export LARCH_PATH=/usr/local/share/splint/lib/
export LCLIMPORTDIR=/usr/local/share/splint/imports/
 
修改环境变量:
export PATH=/usr/local/bin/:$PATH
 

实践

 
实例test.c
#include 
#include 

int main()
{
        unsigned char ch = 128;
        signed char sch = ch;
        int *p = (int*)malloc(1000*sizeof(int));
        printf("%d", sch);
}

[root@localhost test]# splint test.c
Splint 3.1.2 --- 15 Jan 2014

test.c: (in function main)
test.c:6:21: Variable ch initialized to type int, expects unsigned char: 128
  To make char and int types equivalent, use +charint.
test.c:7:20: Variable sch initialized to type unsigned char, expects char: ch
  To ignore signs in type comparisons use +ignoresigns
test.c:9:15: Format argument 1 to printf (%d) expects int gets char: sch
   test.c:9:11: Corresponding format code
test.c:10:2: Path with no return in function declared to return int
  There is a path through a function declared to return a value on which there
  is no return statement. This means the execution may fall through without
  returning a meaningful result to the caller. (Use -noret to inhibit warning)
test.c:10:2: Fresh storage p not released before return
  A memory leak has been detected. Storage allocated locally is not released
  before the last reference to it is lost. (Use -mustfreefresh to inhibit
  warning)
   test.c:8:42: Fresh storage p created
test.c:8:7: Variable p 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)

Finished checking --- 6 code warnings

 

从输出信息可以看出:变量类型转换、内存泄露、返回值等相关问题都被检测了出来。在代码编译之前,对代码使用splint进行检查,可以避免很多不必要的错误。

 

在Linux下,通过man splint可以查看更多的splint选项

 

splint库函数问题

如果代码中涉及到库函数,需要添加库函数支持,才能让splint支持库函数的解析。

splint test.c +posixlib 支持POSIX库

splint test.c +unixlib 支持Unix库

 

你可能感兴趣的:(tools)