No space for zero terminator¶
ID: cpp/no-space-for-terminatorKind: problemSecurity severity: 9.8Severity: errorPrecision: highTags: - reliability - security - external/cwe/cwe-131 - external/cwe/cwe-120 - external/cwe/cwe-122Query 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 identifies calls tomalloc that callstrlen to determine the required buffer size, but do not allocate space for the zero terminator.
Recommendation¶
The highlighted code segment creates a buffer without ensuring it’s large enough to accommodate the copied data. This leaves the code susceptible to a buffer overflow attack, which could lead to anything from program crashes to malicious code execution.
Increase the size of the buffer being allocated by one or replacemalloc,strcpy pairs with a call tostrdup
Example¶
voidflawed_strdup(constchar*input){char*copy;/* Fail to allocate space for terminating '\0' */copy=(char*)malloc(strlen(input));strcpy(copy,input);returncopy;}
References¶
CERT C Coding Standard:MEM35-C. Allocate sufficient memory for an object.
Common Weakness Enumeration:CWE-131.
Common Weakness Enumeration:CWE-120.
Common Weakness Enumeration:CWE-122.