阅读量:95
在 C++ 代码审查中,结合 limits 可以帮助您确保代码的健壮性和安全性
- 检查整数溢出:当涉及到整数运算时,确保操作不会导致溢出。使用
std::numeric_limits检查整数类型的最大值和最小值。
#include
#include
int add(int a, int b) {
if (a > 0 && b > std::numeric_limits<int>::max() - a) {
std::cerr << "Integer overflow detected!"<< std class="hljs-keyword">return std::numeric_limits<int>::max();
}
if (a < 0 && b < std class="hljs-type">int>::min() - a) {
std::cerr << "Integer underflow detected!"<< std class="hljs-keyword">return std::numeric_limits<int>::min();
}
return a + b;
}
- 浮点数精度检查:浮点数运算可能会引入精度问题。使用
std::numeric_limits检查浮点数的精度和表示范围。
#include
#include
#include
double divide(double a, double b) {
if (std::abs(b) <= std::numeric_limits<double>::epsilon()) {
std::cerr << "Division by zero or close-to-zero value detected!"<< std class="hljs-keyword">return std::numeric_limits<double>::quiet_NaN();
}
return a / b;
}
- 检查无符号整数下溢:无符号整数不能为负数,因此需要检查减法操作是否会导致无符号整数下溢。
#include
#include
unsigned int subtract(unsigned int a, unsigned int b) {
if (a < b class="hljs-string">"Unsigned integer underflow detected!"<< std class="hljs-keyword">return std::numeric_limits<unsigned int>::max();
}
return a - b;
}
- 检查数组越界:当访问数组或容器时,确保索引值在有效范围内。
#include
#include
int getElement(const std::vector<int>& vec, size_t index) {
if (index >= vec.size()) {
std::cerr << "Array index out of bounds detected!"<< std class="hljs-keyword">return -1; // 或者抛出异常
}
return vec[index];
}
通过在代码审查中结合 std::numeric_limits,您可以更好地确保代码的健壮性和安全性。这将有助于防止潜在的错误和漏洞,从而提高代码质量。