[metadata]
id = "STR31-C"
type = "rule"
category = "STR"
number = 31
title = "Guarantee that storage for strings has sufficient space for character data and the null terminator"
description = """
Copying data to a buffer that is not large enough to hold that data results in a
buffer overflow. Buffer overflows occur frequently when manipulating strings
[Seacord 2013b]. To prevent such errors, either limit copies through truncation
or, preferably, ensure that the destination is of sufficient size to hold the
character data to be copied and the null-termination character. (SeeSTR03-C. Do
not inadvertently truncate a string.) When strings live on the heap, this rule
is a specific instance ofMEM35-C. Allocate sufficient memory for an object.
Because strings are represented as arrays of characters, this rule is related to
bothARR30-C. Do not form or use out-of-bounds pointers or array
subscriptsandARR38-C. Guarantee that library functions do not form invalid
pointers. This noncompliant code example demonstrates anoff-by-oneerror [Dowd
2006]. The loop copies data fromsrctodest. However, because the loop does not
account for the null-termination character, it may be incorrectly written 1 byte
past the end ofdest.
"""
severity = "High"
likelihood = "Likely"
priority = "P9"
level = "L2"
cert_version = "2016 Edition (Wiki)"
last_modified = "Oct 29, 2025"
[rules.cert_c.STR31-C]
enabled = true
[references]
wiki = "https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+and+the+null+terminator"
cwe = ["CWE-119", "CWE-120", "CWE-123", "CWE-124", "CWE-125", "CWE-126", "CWE-127", "CWE-676", "CWE-122", "CWE-121", "CWE-193"]