在研究corepattern需要讓程序出core, 因此用到的assert, 記錄一下。
寫嚴謹代碼時,也可以使用assert進行嚴格的條件判斷。
函數原型:
#include <assert.h> void assert( int expression );
C++ assert()宏的作用是現計算表達式 expression ,如果其值為假(即為0),那么它先向
stderr打印一條出錯信息,
然后通過
調用 abort 來終止程序運行。(通常會core, 一般謹慎使用)
斷言主要的用處:
1. 可以在預計正常情況下程序不會到達的地方放置斷言 :assert false
2. 斷言可以用於檢查傳遞給私有方法的參數。(對於公有方法,因為是提供給外部的接口,所以必須在方法中有相應的參數檢驗才能保證代碼的健壯性)
3. 使用斷言檢查類的不變狀態,確保任何情況下,某個變量的狀態必須滿足。(如age屬性應大於0小於某個合適值)
4. 斷言core程序時, 會保留完整的信息, 比if...else...在追查問題方面方便.
看代碼:
1 #include <stdio.h> 2 #include <assert.h> 3 #include <string.h> 4 5 void print(const char* arg){ 6 assert(arg != NULL); 7 int len = strlen(arg); 8 char *buf = new char[len + 1]; 9 snprintf(buf, sizeof(buf), "%s", arg); 10 11 assert(strcmp(arg, "test") != 0); 12 puts(buf); 13 14 delete [] buf; 15 } 16 17 int main(int argc, char *argv[]){ 18 if (argc == 2){ 19 print(argv[1]); 20 } 21 22 return 0; 23 }
設置core文件大小: ulimit -c unlimited
編譯: g++ -g test.cpp -o test
執行: ./test test
[liu@localhost test]$ ./test test
test: test.cpp:11: void print(const char*): Assertion `strcmp(arg, "test") != 0' failed.
Aborted (core dumped)
可以用gdb來查看堆棧信息, core狀態保存完整,