When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

Bhj2001's blog

By Bhj2001, history, 4 years ago, In English
 #pragma GCC optimize ("trapv") // kills the program on integer overflows (but is really slow).

This helps a lot in testing. If a solution fails on a particular test case this can help in finding the bug.
This works on my computer but does not work on Codeforces.
Is there an alternative to this on online judges?

  • Vote: I like it
  • +38
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +23 Vote: I do not like it

This is very useful option indeed, just remember, that it does not work with unsigned integers and with casts

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    What do you mean by "does not work with casts"? Does it mean that casts donot happen at all when using this.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +6 Vote: I do not like it

      It will not catch overflow/underflow when casting, say, from long long to int, including implicit casts

»
4 years ago, # |
Rev. 2   Vote: I like it +17 Vote: I do not like it

I compile with these flags and one of them turns on checking for overflows (but slows the program down too). This won't likely help you when submitting to an online judge :(

g++ -std=c++17 -Wshadow -Wall -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG

»
4 years ago, # |
Rev. 2   Vote: I like it +17 Vote: I do not like it

On Codeforces, you can submit with the compiler "Clang++ 17 Diagnostics", which have much more checking than just integer overflow error. However, because test cases on Codeforces are large, you might get time limit exceeded before getting to the desired test case.


See also: Catching silly mistakes with GCC — Codeforces (including tips on how to check integer overflow, array out of bound error, check for precondition in STL algorithm, turn on warnings, etc.)

»
3 years ago, # |
  Vote: I like it +5 Vote: I do not like it

Hi, i used this pragma in my code to detect the overflow in long long int type but it is not working.. this is my code:

void overflow() {
  long long int max = numeric_limits<long long int>::max();
  long long int min = numeric_limits<long long int>::min();
  max += max;
  min -= min;
  cout << max << ":" << min;
}

is there any additional compiler flags that i have to use to detect these bugs? thanks

  • »
    »
    13 months ago, # ^ |
      Vote: I like it +26 Vote: I do not like it

    Sorry for a posting this after 3 years, but I know a one of the all possible solutions and want to share it. You can disable all optimizations and then you can enable trapv:

    #pragma GCC optimize("O0,trapv")
    
    Testing in a custom invocation

    Bhj2001, I hope, that it resolves your initial problem too.

»
13 months ago, # |
  Vote: I like it -50 Vote: I do not like it

Fuck this thing