0

Why is it when I define a pointer to an array of two int's, let's say:

int *data;
data = malloc(sizeof(int)*2);

Then insert some values:

*(data) = 22;
*(data+1) = 466;
*(data+2) = 1000;

Even though the array only has the size of 2, if I print the third element I placed in the vector, it will still show correctly? Is it normal or am I changing memory addresses where I shouldn't be meddling with?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Zetsuno
  • 97
  • 1
  • 9
  • 4
    *"or I'm changing memory addresses where I shouldn't be meddling with?"* **That's a bingo!** Access past array bounds is undefined behavior. – peppe Jun 21 '15 at 17:20
  • 2
    It's Undefined Behaviour. It might appear to work if there is no conflict with anything else, but anything can happen when you index `data[2]`. – Weather Vane Jun 21 '15 at 17:21
  • 1
    This is what is called an undefined behavior. – Jean-Baptiste Yunès Jun 21 '15 at 17:21
  • 3
    To anyone: please do not spread the bad wording. This [source] is what *leads* to undefined behavior, not what it *is*. Code cannot be undefined behavior, because code and behavior are different categories – the former is producing the latter. – user3125367 Jun 21 '15 at 19:23

0 Answers0