在前段时间的项目开发中遇到了这个断言,看了网上很多资料仍然没有结果,大部分处理方法是:
将项目设置中->配置属性->C/C+±>语言->默认Char无符号,选择是(/J)
这个操作是将项目中的默认char类型更改为无符号char(unsigned char),但是这个方法在现行的VS2010中不管用,现行的VS2010中已经没有这个选项,而且我不确定将项目的默认char类型改变是否会对我的项目造成其它影响,所以我没有采用这个方法。
调试了很久发现我的程序中调用了isspace(判断字符是否为空格)、isprint(判断是否为打印字符)、isalnum(判断字符是否为数字)、isdigit函数,这些函数在isctype.c中,通过查看isctype.c的实现源码发现:
extern "C" int __cdecl _chvalidator(int const c, int const mask)
{
_ASSERTE(c >= -1 && c <= 255);
return _chvalidator_l(nullptr, c, mask);
}
extern "C" int __cdecl _chvalidator_l(_locale_t const locale, int const c, int const mask)
{
_ASSERTE(c >= -1 && c <= 255);
_LocaleUpdate locale_update(locale);
int const index = (c >= -1 && c <= 255) ? c : -1;
return locale_update.GetLocaleT()->locinfo->_public._locale_pctype[index] & mask;
}
由于我项目默认char为有符号类型,其取值范围为[-128 ~ 127],当传入的字符超过127(可能是中文)时,此时char类型值溢出为负数,而当调用之前提到的函数时,则会触发断言_ASSERTE(c> = -1 && c <= 255)。
解决方法:
在调用这些函数时,将参数先强转为无符号char类型(取值范围0~255)
eg: isprint((unsigned char) c);