Skip to content

Latest commit

 

History

History
77 lines (62 loc) · 1.5 KB

bug303.md

File metadata and controls

77 lines (62 loc) · 1.5 KB

无符号数循环问题

找Bug

这段代码有什么问题?

bool equals( class1* val1, class2* val2 ) const
{
  ...
  size_t size = val1->size();
  ...
  while ( --size >= 0 ) {
    if ( !comp(*itr1,*itr2) )
      return false;
    itr1++;
    itr2++;
  }
  ...
}

说明

问题分析:

size 变量是无符号类型(size_t),所以 --size >= 0 条件总是为 true。

当 size 为 0 时:

  • --size 会将其变为一个很大的正数(无符号整数下溢)
  • >= 0 条件仍然为真
  • 循环无法终止,导致无限循环或数组越界

正确的写法:

方法1:使用有符号整数

int size = static_cast<int>(val1->size());
while ( --size >= 0 ) {
  // ...
}

方法2:使用递增循环(推荐)

size_t size = val1->size();
for (size_t i = 0; i != size; i++) {
  if ( !comp(*itr1,*itr2) )
    return false;
  itr1++;
  itr2++;
}

方法3:使用递减但检查是否等于0

size_t size = val1->size();
while ( size > 0 ) {
  --size;
  if ( !comp(*itr1,*itr2) )
    return false;
  itr1++;
  itr2++;
}

要点:

  • 无符号整数下溢:无符号数减到0再减1会变成最大值
  • 循环条件:使用无符号数时要特别注意循环终止条件
  • 最佳实践:使用递增循环或明确检查 > 0 而不是 >= 0

拓展阅读