Accessing memory beyond allocated chunk

suggest change

A pointer into an array containing n elements may be dereferenced only if it is in the range memory through memory + (n - 1). Dereferencing a pointer outside that range causes undefined behavior. For example:

int array[3];
int *beyond_array = array + 3;
*beyond_array = 0; /* Accesses memory that has not been allocated. */

The third line accesses the 4th element in an array that is only 3 elements long, leading to undefined behavior. Similarly, the behavior of the second line in the following code fragment is also not well defined:

int array[3];
array[3] = 0;

Note that pointing past the last element of an array is not undefined behavior (beyond_array = array + 3 is well defined here), but dereferencing it is (*beyond_array is undefined behavior). This rule also holds for dynamically allocated memory (such as buffers created through malloc).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents