C Standard Library Function ABS An Error

xiaoxiao2021-03-06  113

The tape-paid value (ABS.C) provided by VC.NET 7.1 is as follows: int __cdecl abs (int number) {return (Number> = 0? Number: -Number);}

This function is very simple, and there is no problem, but if you carefully figure out, you have discovered a big loophole. Extreme examples, when the function parameter is int_min (32-bit int this value is 0x80000000, i.e., -2147483648), it will be overflow to it, because the maximum positive number of 32-bit int can represent int_max ( 0x7fffffff, ie 2147483647). In fact, negative for INT_MIN is equal to anything, there is no dry (0x80000000, according to the completion of the completion of the rules or 0x80000000). Because the return value of the function declaration is also int, most of the programmer will receive this return value with an INT variable, but the extreme case as described above is almost 100% leader. A simple solution is to always receive return values ​​with a variable of the unsigned int type. Because 32-bit Unsigned Int's value range is 0 to 4294967295 (0xfffffffff), 2147483648 falls within this range, so the absolute value of INT_MIN can be correctly expressed in this range. If this approach is easy to forget, you can write an ABS yourself, just add ASSERT (Number> int_min) in front of the above-described function, or change the return value to the unsigned int type. Why do you have such hidden vulnerabilities in the standard library? Because the computer's storage space is limited, the number of bytes of each type in C must be limited to a limited size, so that the type of the type in the program language really represents the value domain of the corresponding mathematical type value domain. This is the gap between reality and ideals. Not only that, because the symbol type is more than the symbol type, a binary bit is plugged out, but the value domains they can represent are different. But programmers write procedures often intentionally or unintentionally ignored this difference, and is unwilling to face reality (as some programmer call functions never check the return value). They use the types in the program like the use of ideal mathematical types. The European Arianna rocket explosion is the most obnected lesson of this mistake. In this case, every C programmer has a responsibility to keep such a rule: "Refrequently ask: Is this variable or expression type overflow or overflow?" ("Programming Jing-Microsoft preparations high quality unclear C procedures" P80, Steve MAGUIRE).

转载请注明原文地址:https://www.9cbs.com/read-100749.html

New Post(0)