Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The C Secure Coding Rules Draft Technical Specification [ISO/IEC TR TS 17961] defines the following terms:

...

Following is an incomplete list of C library functions to which this rule applies to.

Library functions that take a pointer and integer

The following standard library functions take a pointer argument and a size argument, with the constraint that the pointer must point to a valid memory object of at least the number of bytes or wide characters (as appropriate) indicated by the size argument. 

fgets()

fread()*

fwrite()*

mblen()

memchr()

memset()

fgetws()

wmemchr()

wmemset()

mbrlen()

tmpnam_s()

gets_s()

getenv_s()

memset_s()

strerror_s()

strnlen_s()

asctime_s()

ctime_s()

wcscpy_s()

wcsncpy_s()

wmemcpy_s()

wmemmove_s()

wcscat_s()

wcsncat_s()

wcsnlen_s()

 

 

 

...

aligned_alloc()

calloc()

malloc()

realloc()

Other Library Functions

memcpy()

memmove()

vsnprintf()

vswprintf()swprintf()

strftime()

strxfrm()

snprintf()

 

...

In this noncompliant code example, the effective type of *p is float, and the derived type of the expression n is int. This is calculated using the first rule from TR from TS 17961's definition of derived types (see Section 4, "Definitions section " [ISO/IEC TR TS 17961]). Because n contains the result of a sizeof expression, its derived type is equal to the type of the operand, which is int.

...

In this noncompliant code example, the size of n could be greater than the size of *p. Also, the effective type of *p (int) is different than from the effective type of *q (float).

...

In this noncompliant code example, the value of n is greater than the size of T, that is, sizeof(wchar_t). But the derived type of expression n (wchar_t *) is not the same as the type of T because its derived type will be equal to the type of p, which is wchar_t*. The derived type of n is calculated using the first rule from TR from TS 17961's definition of derived types (see Section 4, "Definitions" [ISO/IEC TR TS 17961]). Because n here is a sizeof expression, its derived type is equal to the type of the operand (p), which is wchar_t *.

...

In this noncompliant example, a diagnostic is required because the value of n is not computed correctly, allowing a possible write past the end of the object referenced by p.

Code Block
bgColor#FFcccc
void f4(char p[], const char *q) {
  const size_t n = sizeof(p); 
  if ((memcpy(p, q, n)) == p) {  /* violation */
    /* ... */
  }
 
  /* ... */
}

...

This compliant solution ensures that the n is equal to the size of the character array.

...

Tool

Version

Checker

Description

PRQA QA-C
Include Page
PRQA_V
PRQA_V
 2931Fully implemented

Related Guidelines

...

...

TS 17961(Draft) Forming invalid pointers by library functions [libptr]

Bibliography

...

...

Programming Languages,Their Environments and System Software Interfaces

...