C ++ automatic way to truncate print error at runtime

I just joined a team that has thousands of lines of code, for example:

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

      

The compiler gives good warnings: "Converting a value from bit XX to 'short" causes truncation. I have been told that there are no cases where truncation actually occurs, but I seriously doubt it.

Is there a good way to inject checks into each case that has an effect:

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

      

before every assignment? Doing this manually will take more time and effort than I would like to use, and writing a script that reads the warnings and adds this stuff to the correct file as well as the necessary inclusions seems to be overkill - especially since I expect someone else to have done this (or something like that).

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 I can convince management that this is the problem.

+3


source to share


2 answers


You can 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 can break the code it passes short

as a template argument and probably in other cases, so don't define it where it breaks the assembly. And you might need to add operator overloads to get normal arithmetic to work with the wrapper.

+5


source


Perhaps you can write a plugin for gcc to detect these truncations and emit a function call that checks that the conversion is safe. You can write these plugins in C or Python . If you prefer to use clang, it also supports the plugins entry .



I think the easiest way to do this is to force the plugin to convert the unsafe listing from int

to short

to call the function _convert_int_to_float_fail_if_data_loss(value)

. I'll leave this as an exercise for the reader on how to write such a plugin.

+1


source







All Articles