This question already has an answer here:
Based on my basic knowledge about C++, I assumed following code will have run-time error. Because compiler has not allocate any space for the
y pointer, and I should add the
y = new int; before assigning value to
Am I wrong or compiler has allocate space for
y pointer implicitly? (I compiled my code with Dev-C++ 184.108.40.206.)
using namespace std;
int main(int argc, char *argv)
x = new int;
*x = 42;
cout << *x << "\n";
*y = 13;
cout << *y << "\n";
Best How To :
Section 4.1 states:
An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.
Undefined means anything can happen - there is no guarantee.
From Wiki Making pointers safer
A pointer which does not have any address assigned to it is called a wild pointer. Any attempt to use such uninitialized pointers can cause unexpected behavior, either because the initial value is not a valid address, or because using it may damage other parts of the program. The result is often a segmentation fault, storage violation or wild branch (if used as a function pointer or branch address).