Potentially overflowing call to snprintf¶
ID: cpp/overflowing-snprintfKind: problemSecurity severity: 8.1Severity: warningPrecision: highTags: - reliability - correctness - security - external/cwe/cwe-190 - 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
The return value of a call tosnprintf is the number of characters thatwould have been written to the buffer assuming there was sufficient space. In the event that the operation reaches the end of the buffer and more than one character is discarded, the return value will be greater than the buffer size. This can cause incorrect behavior, for example:
Example¶
#define BUF_SIZE (32)intmain(intargc,char*argv[]){charbuffer[BUF_SIZE];size_tpos=0;inti;for(i=0;i<argc;i++){pos+=snprintf(buffer+pos,BUF_SIZE-pos,"%s",argv[i]);// BUF_SIZE - pos may overflow}}
Recommendation¶
The return value ofsnprintf should always be checked if it is used, and values larger than the buffer size should be accounted for.
Example¶
#define BUF_SIZE (32)intmain(intargc,char*argv[]){charbuffer[BUF_SIZE];size_tpos=0;inti;for(i=0;i<argc;i++){intn=snprintf(buffer+pos,BUF_SIZE-pos,"%s",argv[i]);if(n<0||n>=BUF_SIZE-pos){break;}pos+=n;}}
References¶
cplusplus.com:snprintf.
Red Hat Customer Portal:The trouble with snprintf.
Common Weakness Enumeration:CWE-190.
Common Weakness Enumeration:CWE-253.