简体   繁体   English

c++ 中的缓冲区溢出 [暂停]

[英]buffer overflow in c++ [on hold]

How do i fix the code to include the appropriate bounds checking.如何修复代码以包含适当的边界检查。

~ #include int main(void) { int vals[10]; ~ #include int main(void) { int vals[10];

  size_t count;

  size_t which;

  cout << "How many values should be stored in the array?” <<endl;

  cin >> count;


  for (size_t i = 0; i < count; i++)

 { vals[i] = count - i; }

  cout << "Which value do you wish to retrieve? ";
  cin >> which;

  cout << "Your value is " << vals[which] << endl;

  return 0;
} ~

You can use std::size to check the number of elements in the array before indexing:您可以使用std::size在索引之前检查数组中的元素数:

#include <algorithm>
#include <iterator>

//...

std::cin >> count;
count = std::min(std::size(vals), count);

for (size_t i = 0; i < count; i++)
    vals[i] = count - i;

//...

if(which < count) 
    std::cout << "Your value is " << vals[which] << "\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM