CodeQL documentation

No space for zero terminator

ID: cpp/no-space-for-terminator
Kind: problem
Security severity: 9.8
Severity: error
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-131
   - external/cwe/cwe-120
   - external/cwe/cwe-122
Query 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 to malloc that call strlen 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 replace malloc, strcpy pairs with a call to strdup

Example


void flawed_strdup(const char *input)
{
	char *copy;

	/* Fail to allocate space for terminating '\0' */
	copy = (char *)malloc(strlen(input));
	strcpy(copy, input);
	return copy;
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy