Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Corected a typo and clarified first NCCE.

...

Wiki Markup
The C99 standard \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] identifies fourthe following distinct situations in which undefined behavior (UB) can arise as a result of invalid pointer operations:

UB

Description

Example Code

43

Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that does not point into, or just beyond, the same array object.

#Forming Out Of Bounds Pointer

44

Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that points just beyond the array object and is used as the operand of a unary * operator that is evaluated.

#Dereferencing Past The End Pointer, #Using Past The End Index

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2e9461601cc2f6ee-51f79871-436d4656-96c2a625-233a658a2bfb5c8e4ac8e76a"><ac:plain-text-body><![CDATA[

[46

CC. Undefined Behavior#ub_46]

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]).

[#Apparently Accessible Out Of Range Index]

]]></ac:plain-text-body></ac:structured-macro>

59

An attempt is made to access, or generate a pointer to just past, a flexible array member of a structure when the referenced object provides no elements for that array.

#Pointer Past Flexible Array Member

103

The pointer passed to a library function array parameter does not have a value such that all address computations and object accesses are valid.

#Invalid Access By Library Function

...

In the following noncompliant code example the function f() attempts to validate the index before using it as an offset to the statically allocated table of integers. However, the function fails to reject negative index values. When index is less than zero, the behavior of the addition expression in the return statement of the function is undefined 43. On some implementations, the addition alone can trigger a hardware trap. On other implementations, using the result of the addition or dereferencing it can also addition may produce a result that when dereferenced can trigger a hardware trap. Other implementations still may produce a dereferenceable pointer that points to an object distinct from table. Using such a pointer to access the object may lead to information exposure or cause the wrong object to be modified.

Code Block
bgColor#ffcccc
enum { TABLESIZE = 100 };

static int table[TABLESIZE];

int* f(int index) {
  if (index < TABLESIZE)
    return table + index;

  return NULL;
}

...