程式扎記: [ C/C++ 常見問題 ] Check whether an integer overflow occurs at runtime?

標籤

2013年2月20日 星期三

[ C/C++ 常見問題 ] Check whether an integer overflow occurs at runtime?


來源自 這裡
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
  1. /* compile with gcc -ftrapv */  
  2. #include   
  3. #include   
  4. #include   
  5.   
  6. void signalHandler(int sig) {  
  7.   printf("Overflow detected\n");  
  8. }  
  9.   
  10. int main() {  
  11.   signal(SIGABRT, &signalHandler);  
  12.   
  13.   int largeInt = INT_MAX;  
  14.   int normalInt = 42;  
  15.   int overflowInt = largeInt + normalInt;  /* should cause overflow */  
  16.   
  17.   /* if compiling with -ftrapv, we shouldn't get here */  
  18.   return 0;  
  19. }  
Compile and execute:
$ g++ -ftrapv Test.cpp
$ ./a.out
Overflow detected
已經終止

沒有留言:

張貼留言

網誌存檔