C/C++文件读取报错:stack around the variable 'x' was corrupted.
来源:互联网 发布:阿里云 cdn 清除缓存 编辑:程序博客网 时间:2024/05/01 17:56
学C++学了两天了,《C++程序设计》这书也实在是看不下去了。就自己找了个课题来练习一下,因为在我看来只有项目才能让人在最短的时间内得到最大的提升。在这个课题中有个读取文件的程序让我遇到了这个问题:就是在每次读数据读到最末尾的时候会报错,如下图。
看它字面意思及结果,似乎是数组越界了。因为出错的语句在执行完以后程序并没有强制退出,还可以继续往下执行。
以下是程序源码,代码很乱,凑合着看就行了。
#include<iostream>#include<fstream>using namespace std;void readLine(ifstream &is,char *c,int index);void main(){ifstream ifs;ifstream &iss = ifs;//行读取结果数组。char result[14];//传入引用。ifs.open("abc.txt",ios::in);readLine(iss,result,0);for(short i=0;i<7;i++){if(ifs.eof()){cout<<result<<endl;cout<<"end"<<endl;break;}cout<<result<<endl;//打印当前指针位置。cout<<"The pointer:"<<ifs.tellg()<<endl;readLine(iss,result,(int)ifs.tellg());}//for -- end.cout<<"ifs is closing."<<endl;ifs.close();}void readLine(ifstream &is,char c1[],int index){is.seekg(index);cout<<index<<endl<<endl;char c;for(short i=0;i<15;i++){is.read(&c,sizeof(char)); //读一行数据的代码。if(c == '\n'){ // ①c1[i] = '\0';break;}c1[i] = c;}//for -- end.}后来经过一翻排查才发现这个错误是代码中①号标注处逻辑错误。在标注处的代码块执行条件是,当文件流读到文件中的换行符时。粗一看没什么问题,但其实正是这个条件导致了上文提到的错误。当文件流指针读取到文件的最后一字符时,它就不再是'\n'换行符了。因此,在文件的末尾,行数组将没有结束标志符。进而导致这个数组溢出的错误发生。要解决这个小BUG也很简单,方法有二,一是改变这个 if 块的判断条件:
<span style="white-space:pre"></span>if(c == '\n' || is.eof()){ // ①c1[i] = '\0';break;}二是从根本上解决。我在这个readLine方法中之所以要用for循环来读取完全是因为我的文本文件中的数据是固定格式的,每行数据不超过13个字符。所以我才选择了这种方式。如果想要打开任意文本文件,就不能用这个for块了。而是应该使用while循环。通过判断is.eof()及c=='\n的状态来执行处理。此处就不再贴代码了。毕竟是很简单的东西。之所以写这篇这么没技术含量的博文完全是为了当作对自己学了两天C++的一个交待而已。改完程序后可以看到结果已经正常了。
希望日后我真的能贴出一些很有技术含量的博文来。
0 0
- C/C++文件读取报错:stack around the variable 'x' was corrupted.
- stack around the variable "xxx"was corrupted.
- 浅析stack around the variable was corrupted
- Stack around the variable 'cmdInfo' was corrupted
- Stack around the variable was corrupted
- stack around the variable “XX” was corrupted
- 解决:stack around the variable was corrupted
- 浅析stack around the variable was corrupted
- Stack around the variable was corrupted 解决方案
- stack around the variable "xx" was corrupted
- stack around the variable * was corrupted
- Stack around the variable was corrupted 解决方案
- stack around the variable “” was corrupted
- 错误:stack around the variable * was corrupted
- stack around the variable “” was corrupted问题
- Stack around the variable 'data' was corrupted.
- stack around the variable “” was corrupted
- stack around the variable “res” was corrupted
- 关于extjs5.0下的mixins
- hdu 1690 Bus System
- (Java实现)HTML页面转PDF解决方案
- 使用excel进行数据挖掘(2)----分析关键影响因素
- tar 压缩与解压缩打包命令
- C/C++文件读取报错:stack around the variable 'x' was corrupted.
- leetcode[169]:Majority Element
- Python 字符串操作
- vs中c、c++屏蔽警告
- apache+tomcat 报错 Internal Server Error
- What is the difference between using a script and an animation?
- 网络流 dinic算法 SAP 记录
- XStream 用法总结
- 【练习题】编程把INI文件转换成XML文件