Dangerous use of ‘cin’¶
ID: cpp/dangerous-cinKind: problemSecurity severity: 10.0Severity: errorPrecision: highTags: - reliability - security - external/cwe/cwe-676Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds calls tostd::istream::operator>> onstd::cin without a preceding call tocin.width. Consuming input fromcin without specifying the length of the input is dangerous due to the possibility of buffer overflows.
Recommendation¶
Always specify the length of any input expected fromcin by callingcin.width before consuming the input.
Example¶
The following example shows both a dangerous and a safe way to consume input fromcin.
#define BUFFER_SIZE 20voidbad(){charbuffer[BUFFER_SIZE];// BAD: Use of 'cin' without specifying the length of the input.cin>>buffer;buffer[BUFFER_SIZE-1]='\0';}voidgood(){charbuffer[BUFFER_SIZE];// GOOD: Specifying the length of the input before using 'cin'.cin.width(BUFFER_SIZE);cin>>buffer;buffer[BUFFER_SIZE-1]='\0';}
References¶
Common Weakness Enumeration:CWE-676.