Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239270
  • 博文数量: 91
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 955
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-12 09:38
文章分类

全部博文(91)

文章存档

2017年(1)

2011年(1)

2008年(15)

2007年(74)

我的朋友

分类: LINUX

2008-05-10 08:44:28

出错处理
assert() 函数用法
assert宏的原型定义在中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,
然后通过调用 abort 来终止程序运行。
请看下面的程序清单badptr.c:
#include <iostream.h>
#include <assert.h> //assert(expression) need
int main( void )
{
       FILE *fp;
   
       fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
       assert( fp ); //所以这里不会出错 assert() 里的参数也可以是表达式
       fclose( fp );
   
       fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
       assert( fp ); //所以这里出错
       fclose( fp ); //程序永远都执行不到这里来
       return 0;
}
[root@localhost error_process]# g++ badptr.c -o badptr
[root@localhost error_process]# ./badptr
a.out: badptr.c:13: main: Assertion `fp' failed.
已放弃
使用assert的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。
在调试结束后,可以通过在包含#include 的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:
#include
#define NDEBUG
#include
用法总结与注意事项:
1)在函数开始处检验传入参数的合法性
如:
int resetBufferSize(int nNewSize)
{
//功能:改变缓冲区大小,
//参数:nNewSize 缓冲区新长度
//返回值:缓冲区当前长度
//说明:保持原信息内容不变     nNewSize= 0);
assert(nNewSize =0 && nOffset+nSize= 0);
assert(nOffset+nSize <= m_nInfomationSize);
3)不能使用改变环境的语句,因为assert只在DEBUG个生效,如果这么做,会使用程序在真正运行时遇到问题
错误: assert(i++ < 100)
这是因为如果出错,比如在执行之前i=100,那么这条语句就不会执行,那么i++这条命令就没有执行。
正确: assert(i < 100)
         i++;
            
      
4)assert和后面的语句应空一行,以形成逻辑和视觉上的一致感
5)有的地方,assert不能代替条件过滤

errno

#include
Description
The header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the call returned an error (usually -1), and a function that does succeed is allowed to change errno.
such as:
#include
#include   //sqrt()
#include   //errno and perror need
int main()
{
double d;
d=sqrt((double)-1);
if(errno)
{
perror("sqrt -1 failed");
errno=0;
}
else
cout<<"sqrt -1 ="<return 0;
}
the reault:
$ ./test
sqrt -1 failed: Numerical argument out of domain

perror
perror调用能够地打印系统错误信息,它的原型是
#include
void perror(const char *s)

exit()
好多的参考书都需要头文件#include ,但是我在运行c++程序时,跟本就不需要这个头文件
void exit(int status);

strip
用strip命令处理一个程序意味着用strip命令去除编译好的中的符号,这些符号通常是调试符号。这样做减少了程序对磁盘和内存的占用量,但不好的副作用是让调试变得困难

系统日志函数
 头文件定义了到syslogd的接口,要创建一个日志消息,可使用syslog函数,其原型为
 #include
 void syslog(int priority, char *format, ....)
 format指定写入日志的消息和任何类亿printf的格式说明字符串。

阅读(727) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~