コード仕様_2:防御コード_c/c++

4473 ワード

サブルーチン
  • 中間的で分かりやすい抽象的な
  • を導入する.
  • コードの重複を避ける
  • サブクラス化
  • 非表示シーケンス(必要なシーケンスをマージする操作)
  • 非表示ポインタの動作
  • 移植性向上
  • サブプログラム長:50~150
  • サブルーチンのパラメータ
  • 入力、修正、出力の順序
  • サブルーチンの個数は7個以内
  • である.
    防御プログラミング
    不正データの破壊
  • 外部データ値
  • サブルーチン入力パラメータ値
  • エラーの処理方法
  • 断言する
  • assertはプログラマー自身のエラーをキャプチャするために使用されます.いつまでも起こるべきでないエラー
  • exceptionは、ユーザまたは環境のエラーをキャプチャします.予想されることを捕まえる.
  • 実行するコードを断言
  • に入れないでください.
    堅牢なコード:断言を使用してエラーを処理し、エラー処理を使用します.
    c言語のエラー処理
  • 入力パラメータの妥当性をチェック
  • // crt_assert.c 
    // compile with: /c 
    #include <stdio.h> 
    #include <assert.h> 
    #include <string.h> 
    
    void analyze_string( char *string );   // Prototype 
    
    int main( void )  
    {  
       char  test1[] = "abc", *test2 = NULL, test3[] = "";  
    
       printf ( "Analyzing string '%s'
    "
    , test1 ); fflush( stdout ); analyze_string( test1 ); printf ( "Analyzing string '%s'
    "
    , test2 ); fflush( stdout ); analyze_string( test2 ); printf ( "Analyzing string '%s'
    "
    , test3 ); fflush( stdout ); analyze_string( test3 ); } // Tests a string to see if it is NULL, // empty, or longer than 0 characters. void analyze_string( char * string ) { assert( string != NULL ); // Cannot be NULL assert( *string != '\0' ); // Cannot be empty assert( strlen( string ) > 2 ); // Length must exceed 2 } // Analyzing string 'abc' Analyzing string '(null)' Assertion failed: string != NULL, file assert.cpp, line 25 abnormal program termination

    *例
    void* memcpy(void *dst, const void *src, size_t count)      
    {      
        //     
        assert( (dst != NULL) && (src != NULL) );      
    
        unsigned char *pdst = (unsigned char *)dst;      
        const unsigned char *psrc = (const unsigned char *)src;      
    
        //       
        assert(!(psrc<=pdst && pdst<psrc+count));      
        assert(!(pdst<=psrc && psrc<pdst+count));      
    
        while(count--)      
        {      
            *pdst = *psrc;      
            pdst++;      
            psrc++;      
        }      
        return dst;      
    }

    error
  • ライブラリ関数の呼び出しエラー
  • assertのマクロ定義
    c言語異常
  • C言語の異常メカニズムsetjump longjump関数
  • c++異常処理