Simple Trick to Detect Integer Overflow (C/C++)

Don’t know if problem is with my internet or the website, but I can’t open it. :slightly_frowning_face:

Hmmm … strange. Anyway, here’s a copy-n-paste of it:

// Simon St James (ssjgz) - 2020-XX-XX
// 
// Solution to: TODO - problem link here!
//
//#define SUBMISSION
#define BRUTE_FORCE
#ifdef SUBMISSION
#undef BRUTE_FORCE
#define NDEBUG
#else
#define _GLIBCXX_DEBUG       // Iterator safety; out-of-bounds access for Containers, etc.
#pragma GCC optimize "trapv" // abort() on (signed) integer overflow.
#endif
#include <iostream>
#include <vector>

#include <cassert>

#include <sys/time.h> // TODO - this is only for random testcase generation.  Remove it when you don't need new random testcases!

using namespace std;

template <typename T>
T read()
{
    T toRead;
    cin >> toRead;
    assert(cin);
    return toRead;
}

#if 0
SolutionType solveBruteForce()
{
    SolutionType result;
    
    return result;
}
#endif

#if 0
SolutionType solveOptimised()
{
    SolutionType result;
    
    return result;
}
#endif


int main(int argc, char* argv[])
{
    ios::sync_with_stdio(false);
    if (argc == 2 && string(argv[1]) == "--test")
    {
        struct timeval time;
        gettimeofday(&time,NULL);
        srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
        // TODO - generate randomised test.
        //const int T = rand() % 100 + 1;
        const int T = 1;
        cout << T << endl;

        for (int t = 0; t < T; t++)
        {
        }

        return 0;
    }
    
    // TODO - read in testcase.
    const auto T = read<int>();

    for (int t = 0; t < T; t++)
    {

#ifdef BRUTE_FORCE
#if 0
        const auto solutionBruteForce = solveBruteForce();
        cout << "solutionBruteForce: " << solutionBruteForce << endl;
#endif
#if 0
        const auto solutionOptimised = solveOptimised();
        cout << "solutionOptimised:  " << solutionOptimised << endl;

        assert(solutionOptimised == solutionBruteForce);
#endif
#else
        const auto solutionOptimised = solveOptimised();
        cout << solutionOptimised << endl;
#endif
    }

    assert(cin);
}
3 Likes

while submitting solution should we comment this line #define _GLIBCXX_DEBUG?

In my template? Assuming I haven’t made a mistake, it should be enough to just uncomment the

//#define SUBMISSION

Obviously, only do this when you’ve finished debugging and are sure your solution is correct :slight_smile:

1 Like

Yeah thanks @ssjz

1 Like

The performance impact is noticeable
NwF8je - Online C++0x Compiler & Debugging Tool - Ideone.com (with)
l2fSzm - Online C++0x Compiler & Debugging Tool - Ideone.com (without)

9 Likes

Great - thanks for doing the experiment and providing some hard numbers :slight_smile:

1 Like

I’m trying to use the

#pragma GCC optimize "trapv"

But when i use the following code

#pragma GCC optimize "trapv"
#include<iostream>
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
        int a=10000000,b=1000000000;
        cout<<a<<" "<<b<<'\n';
        int f=a*b;
        cout<<f;
}

It’s not crashing. How do I use it correctly?

1 Like

Interesting - it’s not crashing for me, either. However:

[simon@simon-laptop][17:53:24]
[~/devel/hackerrank/otherpeoples]>cat everule1-ftrapv-test.cpp 
#pragma GCC optimize "trapv"
#include<iostream>
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
        int a,b;
        cin >> a >> b;
        cout<<a<<" "<<b<<'\n';
        int f=a*b;
        cout<<f;
}

[simon@simon-laptop][17:53:32]
[~/devel/hackerrank/otherpeoples]>g++ -std=c++14 everule1-ftrapv-test.cpp  -O3
[simon@simon-laptop][17:53:37]
[~/devel/hackerrank/otherpeoples]>echo "10000000 1000000000" | ./a.out
10000000 1000000000
Aborted (core dumped)

crashes as expected.

I’d guess that with the original version, the compiler is computing the result of a * b at compile-time, and so not triggering the runtime error.

2 Likes

Okay thanks, I thought i was using it incorrectly.

1 Like

Is it safe to submit with this optimization? I read someplace that this increases runtime. Increased runtime is fine as long as it don’t give TLE.

1 Like

Simple Trick to Detect Integer Overflow (C/C++) - #16 by rahul_g :slight_smile:

3 Likes

What do you guys use for a long long infinity?
I generally use int INF = 987654321 for an int infinity. This works everytime, but when I used a random INF value for long long infinity, I got a WA. So I ended up using LLONG_MAX, and whenever I did a = b + c, I had to do this instead.

[Random as in not rand(), some random large value]

if(b == LLONG_MAX or c == LLONG_MAX) a = LLONG_MAX
else a = b + c

Having a long long infinity can make this so much simpler.

1e18. You can add without overflows

1 Like

I often use (1<<29) as an infinity value for int, and would probably use something like (1LL<<60) for a long long infinity.

2 Likes

Wow thank you so much such an awesome post.
You deserve 10 likes from each user.

2 Likes

Sadly, there’s a pretty big flaw in it discovered in this thread:

(see the Important Update in the OP) :frowning:

2 Likes

Will need to read about it a bit more. I am sure it will be useful otherwise it won’t be available in the first place. Just need to figure out when and why.

1 Like

Yes, I suppose: I’ve been using it for ages, and this situation is the first I’ve seen where it breaks :man_shrugging:

3 Likes

Can you please. explain where it fails I am not able to get the program