I'm wondering why my allocation is working. I created ptr
which is a pointer and ptr2
which a pointer on the same location than ptr
.
Here's my code:
int* ptr = malloc(sizeof(int));
int* ptr2 = ptr;
*ptr2 = 1;
ptr2 = ptr+1;
*ptr2 = 2;
At the end I've an array of two integer like that :
ptr[0] = 1
ptr[1] = 2
My question is : why I can affect the value 2 to ptr2
without error or warnings ? I only malloc()
-ed for one integer place in my array, isn't it?
The problem here is, by saying
ptr2 = ptr+1;
you're pointing to out of bound memory. Next upon dererencing, you invoke undefined behavior. Now, the outcome of UB cannot be justified, in any way.
There is nothing inherent in C that stops you from accessing out of bound (or invalid) memory, but the outcome of doing so is UB.
That said, just a suggestion, you should always check the returned value of malloc()
before using that pointer to avoid UB by dereferencing NULL
pointer, in case of malloc()
failure.