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;
}
The problem is that the variable x
is unitialized 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 garbage value and using/accessing that garbage value can lead 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? .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.