今天系统莫明其妙的故障,以前用的好好的客户信息汇总统计突然出现异常,查看日志显示oracle的sql语句异常.
跟踪调试后台发现问题出现在sprintf语句上面,sql预定义 char[8000],然后用sprintf来格式化,结果当语句的数据超过8000的时候就不能正常处理了.
google了一下:
众所周知,sprintf不能检查目标字符串的长度,可能造成众多安全问题,所以都会推荐使用snprintf.
snprintf(_snprintf)的声明是这样的
int _snprintf(
char *buffer,
size_t count,
const char *format [,
argument] ...
);
If len < count, then len characters are stored in buffer, a null-terminator is appended, and len is returned.
If len = count, then len characters are stored in buffer, no null-terminator is appended, and len is returned.
If len > count, then count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.
最常见的错误用法有:
1.
char sa[256]={0};
_snprintf(sa,sizeof(sa),"%s",sb);
//错误原因:当sb的长度>=256的时候,sa将没有'\0'结尾
2.
char sa[256];
_snprintf(sa,sizeof(sa)-1,"%s",sb);
//错误原因:当sb的长度>=255的时候,sa将没有'\0'结尾,忘记给sa初始化
3.
char sa[256];
_snprintf(sa,sizeof(sa)-1,"%s",sb);
sa[sizeof(sa)]=0;
//错误原因:最后一行数组越界
正确的用法
1. //推荐用法
char sa[256];
sa[sizeof(sa)-1]=0;
_snprintf(sa,sizeof(sa),"%s",sb);
if(sa[sizeof(sa)-1]!=0)
{
printf("warning:string will be truncated");
sa[sizeof(sa)-1]=0;
}
2.
char sa[256]={0};
int result = _snprintf(sa,sizeof(sa),"%s",sb);
if(result==sizeof(sa) || result<0)
{
printf("warning:sting will be truncated");
sa[sizeof(sa)-1]=0;
}