Checking for underflow/overflow in C++?

与世无争的帅哥 提交于 2019-11-27 05:25:47

To check for over/underflow in arithmetic check the result compared to the original values.

uint32 a,b;
//assign values
uint32 result = a + b;
if (result < a) {
    //Overflow
}

For your specific the check would be:

if (a > (c-b)) {
    //Underflow
}

I guess if I wanted to do that I would make a class that simulates the data type, and do it manually (which would be slow I would imagine)

class MyInt
{
     int val;
     MyInt(const int&nval){ val = nval;} // cast from int
     operator int(){return val;} // cast to int

    // then just overload ALL the operators... putting your check in
};

//typedef int sint32;
typedef MyInt sint32;

it can be more tricky than that, you might have to wind up using a define instead of a typedef...

I did a similar thing with pointers to check where memory was being written out side of bounds. very slow but did find where memory was being corrupted

Shafik Yaghmour

Cert has a good reference for both signed integer overflow which is undefined behavior and unsigned wrapping which is not and they cover all the operators.

The document provides the following checking code for unsigned wrapping in subtraction using preconditions is as follows:

void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int udiff;
  if (ui_a < ui_b){
    /* Handle error */
  } else {
    udiff = ui_a - ui_b;
  }
  /* ... */
}

and with post-conditions:

void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int udiff = ui_a - ui_b;
  if (udiff > ui_a) {
    /* Handle error */
  }
  /* ... */
}

If you are gcc 5 you can use __builtin_sub_overflow:

__builtin_sub_overflow( ui_a, ui_b, &udiff ) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!