2

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 y pointer.

Am I wrong or compiler has allocate space for y pointer implicitly? (I compiled my code with Dev-C++ 4.9.9.2.)

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{   
    int* x;
    int* y;               
    x = new int;          
    *x = 42;              
    cout << *x << "\n";   
    *y = 13;              
    cout << *y << "\n";   
}
Tail of Godzilla
  • 531
  • 1
  • 6
  • 20

2 Answers2

2

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).

Sadique
  • 22,572
  • 7
  • 65
  • 91
1

Am I wrong or compiler has allocate space for y pointer implicitly?

it has not,and such assignment is Undefined Behaviour. This means it can work and not cause any problems for long time, but suddenly can crash your application. Variable y is actually assigned some random value, and *y=13; assignes 13 to some random memory address which can be a valid memory address of some structure or stack. If you would initialize y to nullptr (or 0, NULL) initially int* y=nullptr;, then you should have application crash.

marcinj
  • 48,511
  • 9
  • 79
  • 100