Muhammad Nada
Muhammad Nada

Reputation: 49

C++ Different types of pointers

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

Answers (3)

moooeeeep
moooeeeep

Reputation: 32502

I see you need some links to documentation:

To wrap it up:

  • You can use the indirection operator (*) to return the object the pointer points to (dereference the pointer).
  • You can only access (read or modify) an object via a pointer, when the pointer actually points to an object (which by default they don't).
  • You can assign the address of an object to the pointer to let the pointer point at it.
  • You can use the address-of operator (&) to acquire the address of an object for assigning it to a pointer.
  • You can use the new operator to create a new object and return the address to it for assigning it to a pointer.
  • You must use delete to eventually destroy objects created using new.
  • When you use pointers, you alone are responsible for the validity of the objects your pointers point to. Don't expect the compiler to warn you when objects are leaked or accessed beyond the end of their lifetime. If you do it wrong, you might observe undefined behavior.
  • Smart pointers can help to keep track of object ownership and take care of proper destruction.

For further reading:

Upvotes: 1

DeepakKg
DeepakKg

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

Carlos
Carlos

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

Related Questions