Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ automatic way to make truncations print an error at runtime

Tags:

c++

truncation

I have just joined a team that has thousands of lines of code like:

int x = 0; 
x=something(); 
short y=x; 
doSomethingImportantWith(y); 

The compiler gives nice warnings saying: Conversion of XX bit type value to "short" causes truncation. I've been told that there are no cases where truncation really happens, but I seriously doubt it.

Is there a nice way to insert checks into each case having the effect of:

if (x>short.max) printNastyError(__FILE,__LINE); 

before each assignment? Doing this manually will take more time and effort than I'd like to use, and writing a script that reads the warnings and adds this stuff to the correct file as well as the required includes seems overkill -- especially since I expect someone has already done this (or something like it).

I don't care about performance (really) or anything other than knowing when these problems occur so I can either fix only the ones that really matter, or so I can convince management that it's a problem.

like image 741
Dale Avatar asked Nov 21 '25 19:11

Dale


1 Answers

You could try compiling and running it with the following ugly hack:

#include <limits>
#include <cstdlib>

template<class T>
struct IntWrapper
{
    T value;

    template<class U>
    IntWrapper(U u) {
        if(u > std::numeric_limits<T>::max())
            std::abort();
        if(U(-1) < 0 && u < std::numeric_limits<T>::min()) // for signed U only
            std::abort();
        value = u;
    }

    operator T&() { return value; }
    operator T const&() const { return value; }
};

#define short IntWrapper<short>

int main() {
    int i = 1, j = 0x10000;
    short ii = i;
    short jj = j; // this aborts
}

Obviously, it may break code that passes short as a template argument and likely in other instances, so undefine it where it breaks the build. And you may need to add operator overloads so that the usual arithmetic works with the wrapper.

like image 190
Maxim Egorushkin Avatar answered Nov 24 '25 07:11

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!