在下面的程序中可以输入什么来访问数组?

What can be inputted in the following program to access the array?

由于 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::vectorstd::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 :)
}

std::array::at:

Returns a reference to the element at specified location pos, with bounds checking. If pos is not within the range of the container, an exception of type std::out_of_range is thrown.

您可能报告错误的其他方式包括:

  1. 在调试中死机:assert(x >= 0 && x < bytes.size() && "I crashed here because you gave me bad input!")
  2. 错误报告给函数调用者:if (x < 0 || x > bytes.size()) { return false; }
  3. 提供更多信息:if (x < 0) { throw my_special_underrun_exception; }if (x > bytes.size()) { throw my_special_overrun_exception; }

最后考虑访问 CppCoreGuidelines 以获得有关如何编写良好代码的大量提示。