So I've been learning C for more than about a year, and never in my studies have I ever thought this was possible:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct exterior
{
int x;
} *ptr;
ptr = (struct exterior *)malloc(sizeof(struct exterior[3]));
ptr[0].x = 1;
ptr[1].x = 2;
ptr[2].x = 3;
ptr[3].x = 4;
ptr[4].x = 5;
ptr[5].x = 6;
printf("%d %d %d %d %d %d", ptr[0].x, ptr[1].x, ptr[2].x, ptr[3].x, ptr[4].x, ptr[5].x);
return 0;
}
So at first I followed the rules of C; I allocated the memory required for 3 structure array elements to a structure pointer. I used to pointer to access the variable that was in the structure, while using an index to specify the structure array element.
For some reason, I then decided to try to access the array element beyond the given limit, even if I knew that the outcome would probably be the program crashing, but I did it anyways.
To my surprise, there was no crash.
Instead, the program worked. It printed out the value I had given to the variable with no problems. How is this possible?
Later on, I tried it with an int
array. It worked as well! Am I doing something wrong?