I know that the malloc, allocate the contigous blocks of memory and return the first address of the allocation, which we keep in a pointer an use it.
I have the following question:
I discovered that if I allocate a number of bytes less than necessary or if try to access something which exceeds the bytes allocated the program still work.
int *ptr;
ptr = (int*)malloc(sizeof(int) * 2);
*ptr = 1;
*(ptr + 1) = 2;
*(ptr + 2) = 3;
After my mind, *(ptr + 2) = 3;
should not work but it still work. I think because *(ptr + 1)
is followed by *(ptr + 2)
in memory.
My question is why it work and if it work like this why we don't use malloc for allocate only the first element of anything?