一例 Run-Time Check Failure #2 - Stack around the variable 'ID' was corrupted.的解决

今天运行一个例程,是一个文件文件里读出数据,然后写入一数据文件中。读入的数据格式如下:

课程表
CourseID CourseName Time Credit
0101 computerPrinciple 86 5
0102 Programming 72 4


源程序如下 : 

#include <iostream>
#include<fstream>


using namespace std;


struct course{
char  num[5];
int hour;
int credit;
};


void createBinaryFile( char * filetxt, char * filedat){
char strBuf[80]= { 0 };
char strBuf2[80] = {0};
char ID[4] = {0};
char name[25] = {0 };
int  rdHour;
int rdCredit;
course aCourse;


ofstream fout(filedat, ios::out);
if(!fout){
cerr<<"D:\\courseFile.dat can not be opened!";
exit (1);
}


ifstream fin(filetxt, ios::in);
if(!fin) {
cerr<<"D:\\courseFile2.txt can not be opened!";
exit (1);
}
fin.getline(strBuf,80);
fin.getline(strBuf2,80);
while(!fin.eof()){
fin>>ID>>name>>rdHour>>rdCredit;
aCourse.hour = rdHour;
aCourse.credit = rdCredit;
int i = 0;
while(ID[i]) {
aCourse.num[i] = ID[i];
++i;
}
aCourse.num[i] = '\0';
fout.write(reinterpret_cast<const char *>(&aCourse),sizeof(course));
}


}


void main(){
createBinaryFile("D:\\courseFile2.txt", "D:\\courseFile.dat");
}


编译无问题,但运行时出现错误:

Run-Time Check Failure #2 - Stack around the variable 'ID' was corrupted. 


经过调试发现,在定义变量时有问题,原来的定义为:

char ID[4]; 

ID所代表的课程号本身就有4个字符,加要上一个表示结束的‘\0'字符,长度应该定义为5. 否则在将ID[]数组逐字符copy给aCourse.num时,没有结束符就会出现错误。


所以,注意在定义字符数组时,长度一定设定为要包含的字符个数再加1. 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值