CWE-1025: Comparison Using Wrong Factors
Description
The code performs a comparison between two entities, but the comparison examines the wrong factors or characteristics of the entities, which can lead to incorrect results and resultant weaknesses.
Submission Date :
Jan. 4, 2018, midnight
Modification Date :
2023-06-29 00:00:00+00:00
Organization :
MITRE
Extended Description
This can lead to incorrect results and resultant weaknesses. For example, the code might inadvertently compare references to objects, instead of the relevant contents of those objects, causing two "equal" objects to be considered unequal.
Example - 1
In the example below, two Java String objects are declared and initialized with the same string values. An if statement is used to determine if the strings are equivalent. However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method:
System.out.println("str1 == str2");String str1 = new String("Hello");String str2 = new String("Hello");if (str1 == str2) {}
System.out.println("str1 equals str2");if (str1.equals(str2)) {}
Related Weaknesses
This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.
Visit http://cwe.mitre.org/ for more details.