C++ assert 断言使用

在研究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状态保存完整,

原文地址:https://www.cnblogs.com/xudong-bupt/p/8420695.html