1

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Couim
  • 735
  • 3
  • 12
  • 29
  • 2
    Undefined behavior is *undefined*. – EOF Jan 08 '17 at 20:03
  • 1
    Possible duplicate of [No out of bounds error](http://stackoverflow.com/questions/9137157/no-out-of-bounds-error) – EOF Jan 08 '17 at 20:04
  • Possible duplicate of [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/questions/26426910/is-accessing-a-global-array-outside-its-bound-undefined-behavior) – nobody Jan 08 '17 at 20:18
  • 1
    Use [Valgrind](http://www.valgrind.org/) if it is available to you; it will point out the error of your ways. Writing outside the bounds of the allocated memory is undefined behaviour. Anything may happen. One of the things that may happen is that you'll get away with it. If you wrote further out of bounds and did more memory allocation, you'd be more likely to get fatal problems. – Jonathan Leffler Jan 08 '17 at 20:36
  • 1
    Neither of the possible duplicates is entirely satisfactory — one deals with overflowing a local array and the other with overflowing a global array. Surely, there must be another duplicate for overflowing dynamically allocated arrays. – Jonathan Leffler Jan 08 '17 at 20:37
  • @JonathanLeffler The undefined behavior doesn't distinguish whether the errant pointer originated with an object of automatic, static, _Thread_local or allocated storage duration. – EOF Jan 08 '17 at 20:45

1 Answers1

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thanks for your answer. So if I want to make it better I can use something like `realloc` ? – Couim Jan 08 '17 at 20:11