來源自 這裡
Question:
Is there any easy way to check whether an integer overflow occurs at runtime?
Answer:
This is compiler-specific, but if you're using gcc/g++ then you can compile with -ftrapv to issue SIGABRT when signed integral overflow occurs.
Below is the sample code:
- Test.cpp
Compile and execute:
Question:
Is there any easy way to check whether an integer overflow occurs at runtime?
Answer:
This is compiler-specific, but if you're using gcc/g++ then you can compile with -ftrapv to issue SIGABRT when signed integral overflow occurs.
Below is the sample code:
- Test.cpp
- /* compile with gcc -ftrapv
*/ - #include
- #include
- #include
- void signalHandler(int sig) {
- printf("Overflow detected\n");
- }
- int main() {
- signal(SIGABRT, &signalHandler);
- int largeInt = INT_MAX;
- int normalInt = 42;
- int overflowInt = largeInt + normalInt; /* should cause overflow */
- /* if compiling with -ftrapv, we shouldn't get here */
- return 0;
- }
沒有留言:
張貼留言