|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CWE-681: Incorrect Conversion between Numeric Types
Description Summary When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.
Example 1 In the following Java example, a float literal is cast to an integer, thus causing a loss of precision. (Bad Code) Example
Language: Java int i = (int) 33457.8f; Example 2 This code adds a float and an integer together, casting the result to an integer. (Bad Code) Example
Language: PHP $floatVal = 1.8345; $intVal = 3; $result = (int)$floatVal + $intVal; Normally, PHP will preserve the precision of this operation, making $result = 4.8345. After the cast to int, it is reasonable to expect PHP to follow rounding convention and set $result = 5. However, the explicit cast to int always rounds DOWN, so the final value of $result is 4. This behavior may have unintended consequences. Example 3 In this example the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned int, amount will be implicitly converted to unsigned. (Bad Code) Example
Language: C unsigned int readdata () { int amount = 0;
...
if (result == ERROR)
amount = -1;
...
return amount;
} If the error condition in the code above is met, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers. Example 4 In this example, depending on the return value of accecssmainframe(), the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned value, amount will be implicitly cast to an unsigned number. (Bad Code) Example
Language: C unsigned int readdata () { int amount = 0;
...
amount = accessmainframe();
...
return amount;
} If the return value of accessmainframe() is -1, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Page Last Updated:
February 20, 2013
|
|
CWE is co-sponsored by the office of Cybersecurity and Communications at the U.S. Department of Homeland Security. This Web site is sponsored and managed by The MITRE Corporation to enable stakeholder collaboration. Copyright © 2006-2013, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation. Contact cwe@mitre.org for more information. |
|||



