Versions Compared

Key

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

C library functions that make changes to arrays or objects usually take at least two arguments: i.)  a pointer to the array/object ii.) an integer indicating the number of elements or bytes to be manipulated. If the arguments are supplied improperly during such a function call, the function may cause the pointer to not point to the object at all or point past the end of the object. This would lead to undefined behavior. 

To make sure that this does not happen, programmers must keep in mind the following rules when using such functions:

  • For func (p,n), where 'p' is the pointer, 'n' is the integer and 'func' is the library function, the value of â€˜n’ should not be greater than the effective size of the pointer. Also, the effective type of the pointer should be compatible with either the derived type of 'n' or unsigned char.
  • For func (p,q, n), where 'p' and 'q' are both pointers, 'n' is the integer and 'func' is the library function, the value of â€˜n’ should not be greater than the effective size of any of the two pointers ('p' and 'q'). The effective type of the 'p' should be compatible with the derived type of 'n' or unsigned char. Similarly, the effective type of the 'p' should be compatible with the effective type of 'q' or unsigned char.
  • For expression E of the form: T* q = func (n), where 'func' is a memory allocation function, the value of 'n' should not be less than sizeof (T). Also, the effective type of 'T' should be compatible with either the derived type of 'n' or unsigned char.

According to the WG14 document:

     Given an integer expression E, the derived type T of E is determined as follows:

...

Note: The first rule from the above definition is applied to non-compliant code/compliant solution 2 and 4 in this page to calculate the derived type of expression 'n' is those examples.

Effective size of a pointer is the size of the object to which it points.

...

The effective size of the pointer 'p' in this example will be sizeof(arr) i.e. 5*sizeof(int).

Effective type of an object is 

C library functions that make changes to arrays or objects usually take at least two arguments: i.)  a pointer to the array/object ii.) an integer indicating the number of elements or bytes to be manipulated. If the arguments are supplied improperly during such a function call, the function may cause the pointer to not point to the object at all or point past the end of the object. This would lead to undefined behavior. 

To make sure that this does not happen, programmers must keep in mind the following rules when using such functions:

...

Noncompliant Code Example

...