CertC++-STR32

Do not pass a non-null-terminated character sequence to a library function that expects a string

Required inputs: IR

Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object. Do not pass a character sequence or wide character sequence that is not null-terminated to a library function that expects a string or wide string argument. 

Noncompliant Code Example

This code example is noncompliant because the character sequence c_str will not be null-terminated when passed as an argument to printf(). (See STR11-C. Do not specify the bound of a character array initialized with a string literal on how to properly initialize character arrays.)

#include <stdio.h>
 
void func(void) {
  char c_str[3] = "abc";
  printf("%s\n", c_str);
}
Compliant Solution

This compliant solution does not specify the bound of the character array in the array declaration. If the array bound is omitted, the compiler allocates sufficient storage to store the entire string literal, including the terminating null character.

#include <stdio.h>
 
void func(void) {
  char c_str[] = "abc";
  printf("%s\n", c_str);
}
Noncompliant Code Example

This code example is noncompliant because the wide character sequence cur_msg will not be null-terminated when passed to wcslen(). This will occur if lessen_memory_usage() is invoked while cur_msg_size still has its initial value of 1024.

#include <stdlib.h>
#include <wchar.h>
 
wchar_t *cur_msg = NULL;
size_t cur_msg_size = 1024;
size_t cur_msg_len = 0;

void lessen_memory_usage(void) {
  wchar_t *temp;
  size_t temp_size;

  /* ... */

  if (cur_msg != NULL) {
    temp_size = cur_msg_size / 2 + 1;
    temp = realloc(cur_msg, temp_size * sizeof(wchar_t));
    /* temp &and cur_msg may no longer be null-terminated */
    if (temp == NULL) {
      /* Handle error */
    }

    cur_msg = temp;
    cur_msg_size = temp_size;
    cur_msg_len = wcslen(cur_msg);
  }
}
Compliant Solution

In this compliant solution, cur_msg will always be null-terminated when passed to wcslen():

#include <stdlib.h>
#include <wchar.h>
 
wchar_t *cur_msg = NULL;
size_t cur_msg_size = 1024;
size_t cur_msg_len = 0;

void lessen_memory_usage(void) {
  wchar_t *temp;
  size_t temp_size;

  /* ... */

  if (cur_msg != NULL) {
    temp_size = cur_msg_size / 2 + 1;
    temp = realloc(cur_msg, temp_size * sizeof(wchar_t));
    /* temp and cur_msg may no longer be null-terminated */
    if (temp == NULL) {
      /* Handle error */
    }

    cur_msg = temp;
    /* Properly null-terminate cur_msg */
    cur_msg[temp_size - 1] = L'\0';
    cur_msg_size = temp_size;
    cur_msg_len = wcslen(cur_msg);
  }
}
Noncompliant Code Example ( strncpy())

Although the strncpy() function takes a string as input, it does not guarantee that the resulting value is still null-terminated. In the following noncompliant code example, if no null character is contained in the first n characters of the source array, the result will not be null-terminated. Passing a non-null-terminated character sequence to  strlen() is undefined behavior.

#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];
  size_t ret = 0;

  if (source) {
    c_str[sizeof(c_str) - 1] = '\0';
    strncpy(c_str, source, sizeof(c_str));
    ret = strlen(c_str);
  } else {
    /* Handle null pointer */
  }
  return ret;
}
Compliant Solution (Truncation)

This compliant solution is correct if the programmer's intent is to truncate the string:

#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];
  size_t ret = 0;

  if (source) {
    strncpy(c_str, source, sizeof(c_str) - 1);
    c_str[sizeof(c_str) - 1] = '\0';
    ret = strlen(c_str);
  } else {
    /* Handle null pointer */
  }
  return ret;
}
Compliant Solution (Truncation, strncpy_s())

The C Standard, Annex K strncpy_s() function can also be used to copy with truncation. The strncpy_s() function copies up to n characters from the source array to a destination array. If no null character was copied from the source array, then the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.

#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>

enum { STR_SIZE = 32 };

size_t func(const char *source) {
  char a[STR_SIZE];
  size_t ret = 0;

  if (source) {
    errno_t err = strncpy_s(
      a, sizeof(a), source, strlen(source)
    );
    if (err != 0) {
      /* Handle error */
    } else {
      ret = strnlen_s(a, sizeof(a));
    }
  } else {
     /* Handle null pointer */
  }
  return ret;
}
Compliant Solution (Copy without Truncation)

If the programmer's intent is to copy without truncation, this compliant solution copies the data and guarantees that the resulting array is null-terminated. If the string cannot be copied, it is handled as an error condition.

#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];
  size_t ret = 0;

  if (source) {
    if (strlen(source) < sizeof(c_str)) {
      strcpy(c_str, source);
      ret = strlen(c_str);
    } else {
      /* Handle string-too-large */
    }
  } else {
    /* Handle null pointer */
  }
  return ret;
}
Risk Assessment

Failure to properly null-terminate a character sequence that is passed to a library function that expects a string can result in buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process. Null-termination errors can also result in unintended information disclosure.

Rule Severity Likelihood Remediation Cost Priority Level
STR32-C High Probable Medium P12 L1
Related Guidelines
Taxonomy Taxonomy item Relationship
ISO/IEC TR 24772:2013 String Termination [CMJ] Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961:2013 Passing a non-null-terminated character sequence to a library function that expects a string [strmod] Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11 CWE-119, Improper Restriction of Operations within the Bounds of a Memory Buffer 2017-05-18: CERT: Rule subset of CWE
CWE 2.11 CWE-123, Write-what-where Condition 2017-06-12: CERT: Partial overlap
CWE 2.11 CWE-125, Out-of-bounds Read 2017-05-18: CERT: Rule subset of CWE
CWE 2.11 CWE-170, Improper Null Termination 2017-06-13: CERT: Exact
Bibliography
[ Seacord 2013]  Chapter 2, "Strings" 
[ Viega 2005] Section 5.2.14, "Miscalculated NULL Termination"
Excerpt from SEI CERT C++ Coding Standard [https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/characters-and-strings-str/str32-c], Copyright (C) 1995-2026 Carnegie Mellon University. See section 9.4. "3rd-Party Licenses" in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

non-null-termination

Possibly passing a non-null-terminated character sequence to a library function that expects a string.

None

False

Options

excluded_arguments

excluded_arguments

Type: dict[bauhaus.analysis.config.QualifiedName, set[int]]

Default:

{
   'snprintf': {0},
   'sprintf': {0},
   'strcpy': {0},
   'strncpy': {0},
   'strxfrm': {0},
   'vsprintf': {0},
   'wcscpy': {0},
   'wcsncpy': {0}
}
Arguments that should not be checked for entries in functions_under_test; first argument/parameter has index 0.
 

functions_under_test

functions_under_test

Type: set[bauhaus.analysis.config.QualifiedName]

Default: {'c16rtomb', 'c32rtomb', 'fputws', 'fscanf', 'fwprintf', 'fwscanf', 'mbrtoc16', 'mbrtoc32', 'printf', 'scanf', 'snprintf', 'sprintf', 'sscanf', 'strcat', 'strchr', 'strcmp', 'strcoll', 'strcpy', 'strcspn', 'strftime', 'strlen', 'strncat', 'strncmp', 'strncpy', 'strpbrk', 'strrchr', 'strspn', 'strtok', 'strxfrm', 'swprintf', 'swscanf', 'vfprintf', 'vfscanf', 'vprintf', 'vscanf', 'vsnprintf', 'vsprintf', 'vsscanf', 'vswprintf', 'vswscanf', 'vwprintf', 'wcschr', 'wcscmp', 'wcscoll', 'wcscpy', 'wcscspn', 'wcsftime', 'wcslen', 'wcsncat', 'wcsncmp', 'wcsncpy', 'wcspbrk', 'wcsrchr', 'wcsspn', 'wcsstr', 'wcstod', 'wcstof', 'wcstok', 'wcstol', 'wcstold', 'wcstoll', 'wcstoul', 'wcstoull', 'wcsxfrm', 'wprintf', 'wscanf'}

Functions which should not use non-null-terminated character sequences for their arguments. All arguments of type pointer to integral type (char, int, etc.) are checked. You can use excluded_arguments if you want to restrict the considered arguments.
 

use_static_semantic_analysis

use_static_semantic_analysis : bool = True

Whether the rule should use the results of the StaticSemanticAnalysis to check for non-null-terminated arguments. This can produce more findings, as additional appearances of unterminated character sequences are investigated, but can also remove false positives. This will not enforce StaticSemanticAnalysis to be enabled, but will not produce any additional results if it is not.