Reputation: 19
I am trying to run a simple C++ program on pointers but the output I am getting is "[Finished in 5.55s with exit code 3221225477]". The Norton Data Protector on my system is blocking the file execution (I guess) but I don't know why? I deactivated the Data Protector but nothing changed. Kindly someone please take a look at the my code and explain to me, what is going on here? Thank You
#include <iostream>
using namespace std;
int main()
{
int x;
int * ptr ;
*ptr = x ;
cout<<ptr;
}
Upvotes: 0
Views: 2973
Reputation: 1
The problem is that the variable x
is uninitialized and you're using the value of an uninitialized variable which leads to undefined behavior. Same goes for variable ptr
, it is also uninitialized and dereferencing it leads to undefined behavior.
*ptr = x ;//undefined behavior because first x is uninitialized and you're using x and second ptr is also unitialized and you're dereferencing ptr
You should do:
int x = 0;
int *ptr = &x;//now ptr is a pointer pointing to variable x
For this very reason it is advised that:
always initialize built in types in local/block scope otherwise they have indeterminate value and using/accessing that value leads to undefined behavior
UB(short for undefined behavior) means anything can happen Including but not limited to access violation error. Check out What does access violation mean?.
Upvotes: 6