Howard Chu hyc@symas.com writes:
And for the record, checking for pointer wraparound is the wrong thing to check. All you want to know is if the new data will fit into the provided buffer. Therefore that is precisely what you should test.
It's also the wrong thing to check according to the C standard, which says that creating a pointer that points outside its object (with a special exception for a pointer that points one element beyond the end of an array) invokes undefined behavior. The program is then permitted to turn your computer into orange goo or do something else unpleasant.
The root of this "bug" (I think it's highly arguable whether gcc breaking broken "security" checks can really be called a bug) is the same as the root of many other complaints about gcc's optimizer, namely that compilers are permitted to take advantage of the assumption that programs won't do something undefined to optimize code and gcc is always becoming more aggressive about optimizing code.
It's also important to note that gcc is only just catching up to commercial compilers here. In the discussion of this bug on the gcc list, a very long list of compilers were identified that do exactly the same optimization that gcc does, including AIX's xlc and Intel's compiler. Many have been doing this optimization for years. So any bugs in programs surfaced by this gcc behavior have been there for years and trigger with other compilers.