반응형

정적코드분석

컴퓨터 소프트웨어를 분석하는 방법 가운데 하나로 그 소프트웨어로부터 만들어진 프로그램을 실제로 실행해보지 않고 분석하는 방법이다. (프로그램을 실행해보고 분석하는 방법은 동적 프로그램 분석이다). 대부분의 경우 원시 코드의 형태를 가지고 분석을 수행하지만 목적 코드의 형태를 가지고 분석하는 경우도 있다. 일반적으로 사람이 어느 정도 프로그램에 대한 이해를 바탕으로 자동화된 도구를 이용해서 분석하는 것을 정적 프로그램 분석이라고 부른다. (from wiki)

 

정적코드분석이 무엇인지 더 자세히 알아보기 위해서 c++ 언어의 정적코드분석 툴중에 하나인 cppcheck를 예를 들어 설명해 보겠다.

아래의 소스코드는 아무런 에러없이 컴파일이 잘 된다.

using namespace std;

int main()
{
    char *pBuf = NULL;
    char *pBuf1 = NULL;
    FILE *pFile;
    char szBuf[1024];
    vectorstList(4, 1);
    vector::iterator itr;

    pBuf = (char *)malloc( 1024 );
    pBuf1 = (char *)malloc( 1024 );

    pFile = popen("pwd", "r");
    if ( pFile != NULL ) {
        if ( fgets( szBuf, sizeof(szBuf), pFile ) != NULL ) {
            printf("pwd : %s", szBuf);
        }
        fclose(pFile);
    }

    stList.push_back(2);
    stList.push_back(3);

    printf("stList : ");
    for ( itr= stList.begin(); itr != stList.end(); itr++ ) {
        printf("%d ", *itr);
    }
    printf("\n");

    for ( itr= stList.begin(); itr != stList.end(); itr++ ) {
        if ( *itr == 1 ) {
            stList.erase(itr);
            itr--;
        }
    }

    printf("stList : ");
    for ( itr= stList.begin(); itr != stList.end(); itr++ ) {
        printf("%d ", *itr);
    }
    printf("\n");

    delete pBuf1;
    return 1;
}

 

 

1# g++ -g -Wall -o test test.cpp

2# ./test
3pwd : /usr/esm/src/module/test
4stList : 1 1 1 1 2 3
5stList : 2 3
6#
 
 

하지만 정적코드분석 툴인 cppcheck 를 이용하면 소스코드의 버그를 발견할 수 있다.

1# cppcheck test.cpp

2Checking test.cpp...
3[test.cpp:50]: (error) Memory leak: pBuf
4[test.cpp:49]: (error) Mismatching allocation and deallocation: pBuf1
5[test.cpp:24]: (error) Mismatching allocation and deallocation: pFile
6[test.cpp:38]: (error) Dangerous iterator usage. After erase the iterator is invalid so dereferencing it or comparing it with another iterator is invalid.
7#

 
 

cppcheck 에서 발견한 버그들은 Memory leak, Mismatching allocation and deallocation, Dangerous iterator usage 와 같은 버그들이 발견되었다.

정적소스코드 분석툴을 이용하여 모든 버그를 발견할 수는 없겠지만 프로그래머가 실수할 수 있는 부분에 대해서 다시 점검할 수 있도록 도와준다고 할 수 있겠다. 또는 미숙한 프로그래머에게는 좋은 학습도구가 될 수 있을 것으로 보인다.

[참고]
위키피디아 : List of tools for static code analysis
위키피디아 : cppcheck



http://godway1225.blog.me/80120146362


반응형

+ Recent posts