Skip to content

Unsafe use of snprintf and vsnprintf return values

Description

The snprintf() and vsnprintf() functions return the total length of the string they tried to create, which can be larger than the size of the destination buffer. Using this return value unsafely, e.g., as an index to write to the destination buffer, can cause memory corruption.

Examples

Insecure Code

c
int len = snprintf(buf, 10, "Hello, %s!", user_input); buf[len] = '\0';

Secure Code

c
int len = snprintf(buf, 10, "Hello, %s!", user_input); if (len >= 10) { /* handle error */ } else { buf[len] = '\0'; }

Remediation

Check the return value of snprintf() and vsnprintf() to ensure it does not exceed the size of the destination buffer before using it.

Rule Details

FieldValue
IDCODE-0744
CategoryInjection
SeverityMEDIUM
CWECWE-120
ConfidenceMEDIUM
ImpactHIGH
LikelihoodMEDIUM
ExploitabilityMODERATE
Tagsbuffer overflow, memory corruption
OWASPN/A

References