c++ - 在下面的程序中可以输入什么来访问数组?
问题描述
由于x
没有真正验证并通过 scanf 接收,因此应该有可能被污染的数据可用于访问bytes
.
代码(不是真正合乎逻辑地做任何有成效的事情):
void getMyBytes(){
int x, byte;
int bytes[20];
scanf("%u %u", &x, &byte);
bytes[x-1] = byte;
}
此代码的一个已知简单(丑陋)修复是:
void getMyBytes(){
int x, byte;
int bytes[20];
scanf("%u %u", &x, &byte);
if (x > sizeof(bytes)/sizeof(*bytes)) return; --> validation fix
bytes[x-1] = byte;
}
我可以在 scanf 中输入哪些输入以便我可以访问bytes
?
解决方案
这取决于您的应用程序,但在访问您的内部成员时,您应该始终绑定检查外部输入。如何报告这取决于您。但是考虑使用std::vector
orstd::array
来帮助你。在您的示例中:
void getMyBytes(){
int x, byte;
std::array<int, 20> bytes; // Bad name btw, an int is very unlikely to be a byte.
scanf("%u %u", &x, &byte); // scanf is not type safe. Consider using cin <<
bytes.at(x-1) = byte; // Automatically bound checks for you and will throw an exception
// in the case that you are out of bounds. Very useful :)
}
返回对指定位置 pos 的元素的引用,并进行边界检查。如果 pos 不在容器的范围内,则抛出 std::out_of_range 类型的异常。
您可能会报告错误的其他方式包括:
- 调试中的硬死:
assert(x >= 0 && x < bytes.size() && "I crashed here because you gave me bad input!")
- 向函数调用者报告错误:
if (x < 0 || x > bytes.size()) { return false; }
- 抛出更多信息:
if (x < 0) { throw my_special_underrun_exception; }
和if (x > bytes.size()) { throw my_special_overrun_exception; }
最后考虑访问CppCoreGuidelines以获取有关如何编写好的代码的大量提示。
推荐阅读
- java - 针对特定表格布局裁剪单元格数据。iText 2.1.7
- kotlin - Kotlin:groupBy 并转换为其他对象
- cordova - -bash:离子:找不到命令(无法安装任何版本)
- lua - 多键元组映射 Lua 中的多值元组
- jq - 如何扩展变量值来构建一个
- heap-memory - 如何在独立配置中通过 CLI 更改 keycloak jvm 参数
- sql-server - 更新在表中存储为 varchar 的 XML
- amazon-web-services - Amazon ECR 注册表作为私有注册表
- php - 反序列化 JSON 数组 php
- python - Python:在文本文件中搜索字符串并显示匹配的行