在Code::Blocks调试时变量出现异常值的问题排查
问题:调试C代码时char变量出现奇怪符号的原因
我从GitHub获取了一段读取盒子尺寸文本文件的C代码,功能是读取盒子各项尺寸信息,代码片段如下:
void inputboxlist(void) { short int n; int errnum; char lbl[5], dim1[5], dim2[5], dim3[5], boxn[5], strxx[5], stryy[5], strzz[5]; strcpy(strtemp, filename); strcat(strtemp, ".txt"); if ( (ifp=fopen(strtemp,"r")) == NULL ) { errnum = errno; fprintf(stderr, "Value of errno: %d\n", errno); printf("Cannot open file %s", strtemp); fprintf(stderr, "Error opening file: %s\n", strerror( errnum )); exit(1); } tbn = 1; if ( fscanf(ifp,"%s %s %s",strxx, stryy, strzz) == EOF ) { exit(1); } xx = atoi(strxx); yy = atoi(stryy); zz = atoi(strzz); while ( fscanf(ifp,"%s %s %s %s %s",lbl,dim1,dim2,dim3,boxn) != EOF ) { boxlist[tbn].dim1 = atoi(dim1); boxlist[tbn].dim2 = atoi(dim2); boxlist[tbn].dim3 = atoi(dim3); boxlist[tbn].vol = boxlist[tbn].dim1 * boxlist[tbn].dim2 * boxlist[tbn].dim3; n = atoi(boxn); boxlist[tbn].n = n; while (--n) { boxlist[tbn+n] = boxlist[tbn]; } tbn = tbn+atoi(boxn); } --tbn; fclose(ifp); return; }
在Code::Blocks中调试这段代码时,运行到定义char类型变量的行后,变量列表中出现大量奇怪符号(如图:调试时变量乱码截图),请问出现该问题的原因是什么?
原因分析
- 栈变量未初始化导致的垃圾值:你定义的这些
char数组都是栈上的局部变量,C语言不会自动初始化栈内存空间,变量创建后会保留栈中之前遗留的随机垃圾数据,调试器显示的就是这些未被清理的原始内存内容,这是变量初始状态的正常现象,并非程序执行出错。 - 调试器的内存展示逻辑:Code::Blocks的调试器会直接读取变量对应的内存区域,对于未初始化的字符数组,它会把内存里的原始字节当作ASCII字符解析,那些无法识别的字节就会显示成奇怪符号。
- 代码存在缓冲区溢出风险:额外提醒,你的代码中使用
fscanf("%s")读取字符串到固定长度的char数组时,没有限制读取长度(比如数组长度为5,应该用%4s来预留字符串结束符\0的位置),如果输入的字符串超过数组长度,会触发缓冲区溢出,那时的乱码就可能是溢出破坏内存后的结果,会引发程序崩溃或异常行为。
内容的提问来源于stack exchange,提问作者shongololo
相关产品推荐
相关产品推荐

