UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

6.10.4.  Overwriting dynamic memory

Array manipulation in C is done with no check that the index used to access an element is within the correct limits. Pointers and arrays are identical (from the point of view of the compiler) due to this behavior, and thus the square brackets can be used with any value to access any element. This behavior is the same for the case of dynamic memory, that is, if a portion of dynamic memory is reserved for a pointer and it is used as an array with an index outside the correct size, the execution proceeds with no check at all. The following code fragment illustrates this situation.

struct point_info 
{
  int x;
  int y;
}; 

struct point_info *points;

points = (struct point_info *)malloc(100 * sizeof(struct point_info));
points[356].x = 10;
points[356].y = 20;

The index used to access the elements in the last two lines is outside the array boundaries, thus, the program is accessing a memory portion in the heap containing data that is allocated or not. The effect of these operations is unpredictable, but the program performs no check.