我们有两个无符号计数器,我们需要对它们进行比较,以检查一些错误条件:
uint32_t a, b;
// a increased in some conditions
// b increased in some conditions
if (a/2 > b) {
perror("Error happened!");
return -1;
}问题是a和b总有一天会溢出。如果a溢出,它仍然是正常的。但如果b溢出,这将是一个错误警报。如何使这张格子防弹?
我知道制作a和b uint64_t会延迟这个错误警报。但是它仍然不能完全解决这个问题。
===============
让我澄清一点:计数器用于跟踪内存分配,这个问题在dmalloc/chunk.c中发现
#if LOG_PNT_SEEN_COUNT
/*
* We divide by 2 here because realloc which returns the same
* pointer will seen_c += 2. However, it will never be more than
* twice the iteration value. We divide by two to not overflow
* iter_c * 2.
*/
if (slot_p->sa_seen_c / 2 > _dmalloc_iter_c) {
dmalloc_errno = ERROR_SLOT_CORRUPT;
return 0;
}
#endif发布于 2018-06-09 03:12:27
发布的代码实际上似乎没有使用可能回绕的计数器。
代码中的注释所说的是,比较a/2 > b而不是a > 2*b更安全,因为后者可能会溢出,而前者不会。这对于a的类型比b的类型更大。
发布于 2018-06-09 02:59:37
通过强制两个值同时换行,使值在换行时立即规格化。在包装时保持两者之间的差异。
试试这样的东西;
uint32_t a, b;
// a increased in some conditions
// b increased in some conditions
if (a or b is at the maximum value) {
if (a > b)
{
a = a-b; b = 0;
}
else
{
b = b-a; a = 0;
}
}
if (a/2 > b) {
perror("Error happened!");
return -1;
}发布于 2018-06-09 02:56:46
如果使用64位还不够,那么您需要编写自己的"var increase“方法,而不是重载++操作符(如果您不小心,这可能会弄乱您的代码)。
该方法只会将var重置为“0”或其他有意义的值。
https://stackoverflow.com/questions/50766828
复制相似问题