C++使用数组指针统计字符时出现访问违规错误的排查
字符统计代码访问违例错误原因分析
需求:使用char和int数组统计文本字符(禁止使用map),编写的代码如下:
int* counterCPU = new int[256]{ 0 }; char *cstrCPU = new char[book.length() + 1]; strcpy(cstrCPU, book.c_str()); CountCPURealisation(cstrCPU, counterCPU);
void CountCPURealisation(char* book, int* counter) { int lenght = strlen(book); for (int i = 0; i < lenght; i++) { counter[book[i]]++; } }
运行时在counter[book[i]]++;行触发错误:0xC0000005: Access violation reading location,尝试替换*为&无效。
错误原因
核心问题是char类型的符号属性:C++中默认char是有符号类型,当文本中包含ASCII值大于127的字符(比如扩展ASCII字符、非英文字符)时,这些字符会被解析为负数。而counter数组的有效下标范围仅为0到255,用负数作为下标会访问到数组内存边界之外的区域,直接触发内存访问违例。
修复方案
- 在使用字符作为下标时,强制转换为无符号类型,确保下标落在合法范围内:
counter[static_cast<unsigned char>(book[i])]++; - 直接修改函数参数类型为无符号字符指针,从根源避免符号解析问题:
void CountCPURealisation(unsigned char* book, int* counter) { int length = strlen(reinterpret_cast<char*>(book)); for (int i = 0; i < length; i++) { counter[book[i]]++; } }
额外验证
可以顺便确认book是否为合法的C字符串(确保没有嵌入式空字符导致strlen计算长度错误),但这不是本次错误的触发原因。
内容的提问来源于stack exchange,提问作者JohnBuiloer
相关产品推荐
相关产品推荐

