⬅ Previous Next ➡

Pointers & Memory Management

Pointers & Memory Management in C++
  • Pointers store the address of another variable.
  • Pointer arithmetic is mainly used with arrays (moving pointer element by element).
  • C++ supports dynamic memory allocation using new and deallocation using delete.
  • Always handle null and dangling pointers to avoid crashes.

1) Pointers Basics

  • & gives the address of a variable.
  • * (dereference) gives the value at the stored address.
#include <iostream>
using namespace std;

int main() {
    int a = 10;
    int *p = &a;

    cout << "a = " << a << endl;
    cout << "Address of a = " << &a << endl;
    cout << "p = " << p << endl;
    cout << "*p = " << *p << endl;

    return 0;
}

2) Pointer Arithmetic (With Arrays)

  • If p points to an array element, then:
    • p + 1 moves to next element (by sizeof(type))
    • *(p + i) is same as arr[i]
#include <iostream>
using namespace std;

int main() {
    int arr[4] = {10, 20, 30, 40};
    int *p = arr;

    cout << *p << endl;      // 10
    cout << *(p + 1) << endl; // 20
    cout << *(p + 2) << endl; // 30

    return 0;
}

3) Dynamic Memory Allocation: new and delete

  • new allocates memory at runtime and returns pointer.
  • delete frees memory allocated by new.
  • Always use delete with single object and delete[] with arrays.
3.1) Allocate Single Variable
#include <iostream>
using namespace std;

int main() {
    int *p = new int;  // allocate
    *p = 50;

    cout << "Value: " << *p << endl;

    delete p;   // free
    p = nullptr;

    return 0;
}
3.2) Allocate Dynamic Array
#include <iostream>
using namespace std;

int main() {
    int n = 5;
    int *arr = new int[n];

    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    delete[] arr;
    arr = nullptr;

    return 0;
}

4) Null Pointer

  • A null pointer points to nothing.
  • Use nullptr (modern C++) instead of NULL.
#include <iostream>
using namespace std;

int main() {
    int *p = nullptr;

    if (p == nullptr) {
        cout << "Pointer is null (safe)" << endl;
    }

    return 0;
}

5) Dangling Pointer

  • A dangling pointer points to memory that has been freed or gone out of scope.
  • Fix: set pointer to nullptr after delete.
#include <iostream>
using namespace std;

int main() {
    int *p = new int(99);

    delete p;      // memory freed
    p = nullptr;   // prevents dangling pointer

    if (p == nullptr) {
        cout << "Pointer cleared after delete" << endl;
    }

    return 0;
}

6) Quick Notes

  • Use pointer arithmetic mainly with arrays.
  • new allocates, delete frees.
  • Use delete[] for arrays.
  • Set pointer to nullptr after delete to avoid dangling pointer.
⬅ Previous Next ➡