Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do pointers point to exactly when declared?

Tags:

c++

pointers

If I declare a pointer to use as a "dynamic array" like this:

int *arr;

Without using the new keyword or specifying any size.

Is this bad code? Where exactly does this pointer point to?

And in the case let's say I initialize the array like following:

arr = new int[5];

Then make this call (which works for me):

arr[100] = 10;

Could I overwrite some other data accidentally this way? (so far this never happened to me). is there a "safety threshold" as to how many consecutive blocks that are left free after this pointer declaration?

like image 897
Ahmed Elyamani Avatar asked Jul 01 '26 22:07

Ahmed Elyamani


1 Answers

A pointer variable is just another kind of variable. Its value depends on its storage duration (which isn't shown in your question).

  • Static or thread storage duration objects are zero-initialized.
  • Automatic storage duration objects have an indeterminate value. (These are the regular "local variables" we declare inside functions.)

Reading an indeterminate value invokes undefined behavior. Programs that do that are incorrectly written - even though they may appear to work sometimes. Undefined behavior explicitly imposes no requirements on the implementation, including no requirement for a safety threshold before you start overwriting neighboring data.

But the above only concerns the "dynamic" consequences of invoking undefined behavior (which is what most people tend to focus on). Undefined behavior can have even stranger "static" consequences.

Code that can be inferred ahead-of-time to invoke undefined behavior (whether it's for all cases or just for some values of some expressions in your code) allows the compiler to take less obvious decisions, including removing function calls or even entire branches of code, even in functions that are unrelated to yours (such as modifying the caller of the erroneous function). Raymond Chen has expanded on this in a very informative blog post (that I often refer people to, because it highlights the "static" consequences of UB in great detail).

like image 88
Theodoros Chatzigiannakis Avatar answered Jul 03 '26 11:07

Theodoros Chatzigiannakis