gpt4 book ai didi

c++ - 为什么编译器不使无符号与有符号比较安全?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:52 30 4
gpt4 key购买 nike

<分区>

我们知道,像这样的代码会产生一个警告:

for (int i = 0; i < v.size(); ++i)

解决方案类似于 auto i = 0u; , decltype(v.size())std::vector<int>::size_type但假装我们被迫同时拥有有符号和无符号的值。编译器会自动转换 int成为unsigned int (实际类型无关紧要)。使用显式转换,static_cast<unsigned int>(i)使警告消失,但这很糟糕,因为它只做了与编译器相同的事情,并使重要警告静音!

更好的解决方案是:

if ((i < 0) || (static_cast<unsigned int>(i) < v.size()))

可以理解,C“更接近金属”,因此更不安全。但在 C++ 中,没有任何借口。随着 C++ 和 C 的分歧(正如它们多年来所做的那样),对 C++ 的数百项改进提高了安全性。我非常怀疑这样的更改也会损害性能。

编译器不自动执行此操作是否有原因?

注意:这确实发生在现实世界中。参见 Vulnerability Note VU#159523 :

This vulnerability in Adobe Flash arises because Flash passes a signed integer to calloc(). An attacker has control over this integer and can send negative numbers. Because calloc() takes size_t, which is unsigned, the negative number is converted to a very large number, which is generally too big to allocate, and as a result calloc() returns NULL causing the vulnerability to exist.

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com