Reputation: 49
in the following code I found that same pointer instruction crash the application in a situation while not in other situation.
#include <iostream>
using namespace std;
int main()
{
int *p;
*p = 50; //this instruction causes the crash
int* q = new int;
*q = 50; //this instruction executes ok
cout << "p:" << p << endl;
cout << "q:" << q << endl;
return 0;
}
I want to know why this is the case?
Upvotes: 2
Views: 1179
Reputation: 32502
I see you need some links to documentation:
To wrap it up:
*
) to return the object the pointer points to (dereference the pointer).&
) to acquire the address of an object for assigning it to a pointer.new
operator to create a new object and return the address to it for assigning it to a pointer. delete
to eventually destroy objects created using new
.For further reading:
Upvotes: 1
Reputation: 349
int *p;
This pointer points to nowhere i.e not at any valid address of the process. That's why it crashes
int* q = new int;
Points to a valid address returned by new int
, hence worked
Upvotes: 2
Reputation: 6021
The first pointer is uninitialized. It doesn't point to a memory location that has an int value. So when you deref it on the next line, you get a crash.
The second pointer is initialized to an int that has an actual space in memory. So when you deref it, it finds the value held in that space.
Upvotes: 4