Unsafe use of snprintf/vsnprintf return value may cause buffer overflow

ID

c.buffer_overflow.unsafe_ret_snprintf_vsnprintf

Severity

low

Resource

Buffer Overflow

Language

C / C++

Description

The snprintf() and vsnprintf() functions return the total length of the string they tried to create. Therefore, this return value can be larger than the size of the destination buffer. If it is used unsafely, e.g. as an index to write to the destination buffer, memory corruption might occur.

Rationale

The snprintf() and vsnprintf() functions return the total length of the string they tried to create. Therefore, this return value can be larger than the size of the destination buffer. If it is used unsafely, e.g. as an index to write to the destination buffer, memory corruption might occur.

The following code illustrates a vulnerable pattern detected by this rule:

void copy_string(char *string)
{
	char buf[BUFSIZE];
	size_t length;

	// VULNERABLE: Unsafe use of snprintf/vsnprintf return value may cause buffer overflow
	length = snprintf(buf, BUFSIZE, "%s", string);

	// use length to access buf
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.