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
已經終止

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...