我正在编写一个简单的代码,以从.txt文件中读取系统数据,并收到警告“ C6386:写入'points'时缓冲区溢出:可写大小为'num * 8'字节,但为'16'字节可能会写成”。在我的情况下如何解决?附带代码。
struct point {
int x, y;
};
void main()
{
fstream file;
point* points;
int num,
i = 0;
file.open("C:\\Users\\Den\\Desktop\\file.txt", fstream::in);
if (!file.is_open()) {
cout << "No file found\n";
exit(1);
}
else {
file >> num;
points = new point[num];
}
while (file >> num) {
points[i].x = num; // <- here
file >> num;
points[i].y = num;
i++;
}
file.close();
}
答案 0 :(得分:1)
这只是一个警告,但给出了很好的建议。文件包含的内容超过num
个?警告告诉您应该确保不要在数组末尾书写。具体来说:
此警告表明指定缓冲区的可写范围可能小于用于写入该缓冲区的索引。这可能会导致缓冲区溢出。 [msdn]
此代码不会产生警告(VS2019):
int x, y;
while (i < num && (file >> x >> y)) {
points[i].x = x;
points[i].y = y;
i++;
}
还有更多错误检查要添加。如果file >> num;
失败怎么办?如果num
为负怎么办?如果points = new point[num];
失败(返回nullptr
)怎么办?