Accessing memory beyond allocated chunk
suggest changeA 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).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents