Cast between HRESULT and a Boolean type¶
ID: cpp/hresult-boolean-conversionKind: problemSecurity severity: 7.5Severity: errorPrecision: highTags: - security - external/cwe/cwe-253Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This query indicates that anHRESULT is being cast to a Boolean type or vice versa.
The typical success value (S_OK) of anHRESULT equals 0. However, 0 indicates failure for a Boolean type.
Casting anHRESULT to a Boolean type and then using it in a test expression will yield an incorrect result.
Recommendation¶
To check if a call that returns anHRESULT succeeded use theFAILED macro.
Example¶
In the following example,HRESULT is used in a test expression incorrectly as it may yield an incorrect result.
LPMALLOCpMalloc;HRESULThr=CoGetMalloc(1,&pMalloc);if(!hr){// code ...}
To fix this issue, use theFAILED macro in the test expression.
References¶
Common Weakness Enumeration:CWE-253.