0

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?

octagonlord69
  • 75
  • 2
  • 2
  • 6

1 Answers1

0

When you create on array on C, the program allocates the memory you need for that and gives you the pointer for the first element. So when you say array[0], what you are doing is summing 0 to the base pointer of that array, therefore array[1] is increasing 1(4 bytes to be more precise) to the inicial pointer, so you can see the 2 element and so on (Dont forget that the array is a continous segment of memory, every value is next to his previous one). If you try to reach a position out of the array, the program will not crash, what it will do is read the memory from where it is pointing, which in most cases will most probably be garbish, but C has no problem with it, this language allows you to do pretty much everything!

Hope it helps :)

Pedro Lima
  • 387
  • 2
  • 14
  • An array is not a pointer! E.g. `int a[10];` does not declare a pointer. And the behaviour for accessing an array out of bounds is undefined. It might crash, it might not, it might burn your house or eat the cat. That's the idea of **undefined bahaviour**. No use trying to explain why the code behaves a specific way or speculate.Once you invoke UB, you are outside the language specification. The language does **no way** "allow everything". – too honest for this site Apr 10 '18 at 23:07