c++ - 如何解决 C6386 警告?
问题描述
我正在编写一个简单的代码来从 .txt 文件中读取系统化数据,并收到警告“C6386:写入‘点’时缓冲区溢出:可写大小为‘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();
}
解决方案
这只是一个警告,但它提供了很好的建议。如果文件包含多个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
)怎么办?
更新了完整的错误检查:
struct point {
int x, y;
};
void main()
{
ifstream file("C:\\Users\\Den\\Desktop\\file.txt");
if (!file) {
cerr << "No file found\n";
exit(-1);
}
int num;
if (!(file >> num) || num <= 0) {
cerr << "invalid num\n";
exit(-1);
}
point *points = new point[num];
if (!points) {
cerr << "new failed\n";
exit(-1);
}
int num_items = 0;
while (num_items < num && file >> points[num_items].x >> points[num_items].y) {
num_items++;
}
// Do some work here
delete [] points;
}
将来,考虑使用std::vector
over raw 数组。
推荐阅读
- python - 无法使用烧瓶和 python 3.6 在 Google Flexible App 引擎中导入 matplotlib
- python - 输入输入代码,但运行时不要求我输入
- java - 即使在 xml 文件中定义了操作,也没有任何操作
- excel - !Bloomberg vba价格导入问题
- php - 循环获取最后n组数字
- python - PyQt 启动时加载函数(qml 加载器)
- batch-file - 使用 mvn 依赖:build-classpath 输出文件的行大于 8192 个字符
- mpeg-dash - MPEG-DASH m4s 文件格式
- leaflet - Leaflet.js - 关于折线的问题
- php - 如何在 wordpress 多站点设置中自定义新站点的默认设置?