linux 之assert学习

转自:https://www.cnblogs.com/jackluolei/p/8858787.html
assert是常用于程序调试的一个宏函数,在程序运行时,计算assert()括号里面的表达式,如果为false则报错,并且终止程序的运行,相反继续运行。

简而言之:assert()函数的功能是终止程序以免导致更加严重的错误,同时也用于查找错误。

使用assert()函数的情况:

1.在函数开始时检验传入参数的合法性。

2.一个assert()函数一次只能检测一个条件的合法性。

3.因assert()只在DEBUG下生效,故不能使用改变环境的语句。

4.assert()不能用它来实现条件过滤。

5.频繁的调用assert()语句会影响程序的性能,增加额外的开销。

以下转自:https://blog.csdn.net/u011068702/article/details/62037593

1、assert函数介绍
assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:

#include <assert.h>
void assert( int expression );

assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。

以下为我的理解:
  1. expression 是一个表达式时,表达式成立为真;不成立时为假。
  2. expression 是一个数时,数大于0为真;小于等于0时为假。
  3. expression 是一个指针时,指针的值存在时为真;指针值不存在时为假。

例如:
第1种情况

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	int digit = 1;
	assert(digit>0);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	int digit = 1;
	assert(digit>3);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

第2种情况

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	int digit = 1;
	assert(digit);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	int digit = 0;
	assert(digit);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

第3种情况

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	char *p;
	assert(p);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	char *p = "abc";
	assert(p);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

以下转自:https://blog.csdn.net/kunkliu/article/details/93890641

assert()使用总结:

  1. 在函数开始阶段,检验传入参数的合法性。

例如:

MsgCpy(msg*  dst, msg* src)
{
	assert(dst != NULL);
	assert(src != NULL);
	.......
}
  1. 每个assert()仅仅检验一个条件。否则出错了不知道是哪个条件出错。

  2. 不能在assert()中对变量做出改变。因为assert()仅在Debug模式下起作用。若改变了变量,则Release和Debug模式下会有不同。
    例如:

assert(i++ < 1024)

则在Debug下,i++被执行了。 Release模式下,i++没被执行。

  1. assert()应自成一行,上下有空行。

  2. assert()与条件过滤各自有自己的适用点。不能混淆。

还有就是什么时候assert 起作用。如果是默认情况,加了 #include <assert.h> ,assert函数就起作用。有2种方式,可以使release版本,不启用assert。
1、在源文件里,在包含assert.h之前定义一个NDEBUG宏(表示No Debug),就可以禁用assert.h中的assert宏定义。
比如:

#define NDEBUG
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
	char *p;
	assert(p);
	printf("digit\n");
	return 0;
}

在这里插入图片描述

2、源文件中不定义NDEBUG宏。在编译时加上编译选项 -DNDEBUG ,也可以。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值