GCC's Signed Overflow Trapping With -ftrapv Silently Doesn't Work
2016-05-25 - By Robert Elder
It Doesn't Work In GCC Releases From 2004 to 2014
Whenever the signed/unsigned debates comes up, I usually see someone recommend using the '-ftrapv' flag to catch run-time undefined behaviour, and I thought it was worth writing a short post to point out that it silently doesn't work in many gcc versions that are in common use.
I'm on Ubuntu 14.04 and if I do
sudo apt-get update && sudo apt-get install gcc
and then put this into main.c
#include <limits.h>
#include <stdio.h>
int main(void){
int i = INT_MAX;
return printf("%d\n",i + 1);
}
then run
gcc -ftrapv main.c && ./a.out
the result is
-2147483648
but it does seem to work in clang
clang -ftrapv main.c && ./a.out
gives
Illegal instruction (core dumped)
Broke For Years
It has been documented as though it worked in the man page for some time, but it looks like it has been broken for years:
It Works In Ubuntu 16's GCC
Looking at the bug report above, I saw that the bug was closed in 2014 with a fix, so I launched an EC2 instance to see if I could verify it working on a newer version. I tried launching an Ubuntu 15 instance, but it never came up, but the Ubuntu 16 instance did, and the overflow gets correctly trapped there:
Aborted (core dumped)
Having said this, it looks like this functionality is still flaky: Why does ftrapv not work with optimization?
Seeing that the bug was fixed in 2014 might make you think this is a non-issue, but if you're on Ubuntu, chances are you're not already on the latest LTS which was only released a month ago, so your version likely has this bug.
Arduino With Makefiles For Linux Command Line Programmers
Published 2022-04-25 |
$1.00 CAD |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
How to Get Fired Using Switch Statements & Statement Expressions
Published 2016-10-27 |
Why Is It so Hard to Detect Keyup Event on Linux?
Published 2019-01-10 |
The Most Confusing Grep Mistakes I've Ever Made
Published 2020-11-02 |
Use The 'tail' Command To Monitor Everything
Published 2021-04-08 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|