LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 6 of 27

Pointers and Dynamic Memory

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Pointers and Dynamic Memory · Study material

Pointers in C++ are variables that store memory addresses. With a pointer you can change a variable from another function, walk through an array, build linked lists and trees, and allocate memory at run time with new and delete. They are also the source of the hardest bugs – null dereferences, dangling pointers, memory leaks and double deletes – which is why modern C++ wraps raw pointers in RAII classes and smart pointers. Pointer output questions and memory-management questions appear in almost every C++ interview. This page explains everything with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler with memory sanitizers.

On this page

  • Address-of (&), dereference (*) and nullptr
  • Pointer arithmetic and the link between pointers and arrays
  • const with pointers, pointers to pointers, pointers to structs, void*
  • Dynamic memory: new, delete, new[], delete[]
  • Leaks, dangling pointers, double delete – and how RAII and smart pointers prevent them

Addresses and dereferencing

Every variable lives at some address in memory. &x gives that address, and a variable of type int* can store it. Putting * in front of a pointer dereferences it: *p is the object it points to, which you can read and assign. A pointer that points nowhere should hold nullptr (C++11) – never leave a pointer uninitialized, and never dereference a null pointer.

#include <iostream>

int main() {
    int score = 72;
    int* p = &score;          // p holds the address of score
    std::cout << *p << '\n';  // * dereferences: the value at that address → 72

    *p = 95;                  // writing through the pointer changes score
    std::cout << score << '\n';

    int other = 10;
    p = &other;               // a pointer can be re-pointed
    *p += 5;
    std::cout << score << ' ' << other << ' ' << (p == &other) << '\n';

    int* none = nullptr;      // points to nothing – always initialize pointers
    std::cout << (none == nullptr) << ' ' << sizeof(p) << '\n';
    return 0;
}

Output

72
95
95 15 1
1 8
ExpressionMeaning
int* p;p is a pointer to int (uninitialized!)
p = &x;p now holds x's address
*pthe int p points to
p->mmember m of the object p points to – same as (*p).m
int** pp = &p;pointer to a pointer
int* q = nullptr;points to nothing

In a declaration the * belongs to each name: int* a, b; makes only a a pointer. Declare one pointer per line.

Pointer arithmetic and arrays

Adding n to a pointer moves it by n elements – the compiler multiplies by sizeof the type. Subtracting two pointers into the same array gives the number of elements between them. An array name decays to a pointer to its first element, so a[i] is exactly *(a + i). A pointer one past the last element may be formed (as an end marker) but not dereferenced; going further is undefined behaviour.

#include <iostream>

int main() {
    int a[5] = {10, 20, 30, 40, 50};
    int* p = a;                        // the array name decays to &a[0]
    std::cout << *p << ' ' << *(p + 2) << ' ' << p[4] << '\n';   // p + i moves i elements, not i bytes

    int* end = a + 5;                  // one past the last element: may be formed, never dereferenced
    int sum = 0;
    for (int* it = a; it != end; ++it)
        sum += *it;
    std::cout << sum << ' ' << (end - a) << '\n';                // difference = number of elements

    double d[3] = {1.5, 2.5, 3.5};
    double* q = d;
    ++q;
    std::cout << *q << ' ' << (q - d) << ' '
              << reinterpret_cast<char*>(q) - reinterpret_cast<char*>(d) << " bytes\n";
    return 0;
}

Output

10 30 50
150 5
2.5 1 8 bytes

Watch precedence: *p++ reads *p and then advances the pointer, while (*p)++ increments the value.

const and pointers

Read the declaration from right to left. const int* p – "p is a pointer to a const int": the value cannot be changed through p, but p can point elsewhere. int* const p – "p is a const pointer to int": the value can change, the pointer cannot. Functions that only read through a pointer should take const T*.

#include <iostream>

int main() {
    int x = 1, y = 2;

    const int* p1 = &x;       // pointer to const: can't change *p1, can re-point p1
    p1 = &y;

    int* const p2 = &x;       // const pointer: can change *p2, can't re-point p2
    *p2 = 10;

    const int* const p3 = &y; // both fixed
    std::cout << *p1 << ' ' << x << ' ' << *p3 << '\n';
    // *p1 = 5;   error   p2 = &y;   error   *p3 = 1;   error
    return 0;
}

Output

2 10 2

Dynamic memory: new and delete

Local variables live on the stack and disappear when their block ends. new T(args) creates an object on the heap that lives until you delete it; new T[n] creates an array whose size can be decided at run time and must be released with delete[]. If new cannot get memory it throws std::bad_alloc.

#include <iostream>
#include <string>

int main() {
    int* n = new int(42);                  // one int on the heap
    std::string* s = new std::string("heap text");
    std::cout << *n << ' ' << *s << ' ' << s->size() << '\n';
    delete n;                              // every new needs exactly one delete
    delete s;                              // runs std::string's destructor, then frees

    int count = 5;                         // size known only at run time
    int* arr = new int[count]{};           // array of 5 zeros
    for (int i = 0; i < count; ++i) arr[i] = (i + 1) * (i + 1);
    for (int i = 0; i < count; ++i) std::cout << arr[i] << ' ';
    std::cout << '\n';
    delete[] arr;                          // new[] pairs with delete[]
    arr = nullptr;                         // avoid a dangling pointer
    return 0;
}

Output

42 heap text 9
1 4 9 16 25
AllocateReleaseMixing them up
new T / new T(v)delete p;delete[] on it – undefined behaviour
new T[n]delete[] p;delete on it – undefined behaviour
mallocfreenever mix with new/delete

Pointers to structs and classes

Use -> to reach a member through a pointer. Passing a pointer (or reference) lets a function modify a large object without copying it; checking for nullptr first makes the parameter optional.

#include <iostream>
#include <string>

struct Student {
    std::string name;
    int marks;
};

void add_grace(Student* s, int grace) {    // modifies the caller's object through a pointer
    if (s) s->marks += grace;              // s->marks is (*s).marks
}

int main() {
    Student a{"Asha", 78};
    Student* p = &a;
    add_grace(p, 5);
    std::cout << p->name << ' ' << (*p).marks << '\n';

    Student* list = new Student[2]{{"Ravi", 66}, {"Meera", 91}};
    Student* best = list[0].marks > list[1].marks ? &list[0] : &list[1];
    std::cout << best->name << '\n';
    delete[] list;
    return 0;
}

Output

Asha 83
Meera

Pointers to pointers

A function receives copies of its arguments – including pointers. To let a function change the caller's pointer (for example to allocate memory for it), pass the pointer's address: a pointer to pointer (or a reference to pointer, int*&).

#include <iostream>

void allocate(int** out, int value) {      // pointer to pointer: the function can change the caller's pointer
    *out = new int(value);
}

int main() {
    int x = 7;
    int* p = &x;
    int** pp = &p;
    **pp = 70;                             // two levels of indirection reach x
    std::cout << x << ' ' << *p << ' ' << **pp << '\n';

    int* q = nullptr;
    allocate(&q, 123);
    std::cout << (q != nullptr) << ' ' << *q << '\n';
    delete q;
    return 0;
}

Output

70 70 70
1 123

void* and character pointers

void* can hold the address of any object but cannot be dereferenced or used in arithmetic until it is converted back with static_cast. std::cout treats const char* as a C string and prints the text, not the address.

#include <iostream>

int main() {
    int n = 65;
    void* v = &n;                               // can hold any object address, but cannot be dereferenced
    int* back = static_cast<int*>(v);           // convert back to the real type before use
    std::cout << *back << '\n';

    const char* word = "pointer";
    std::cout << word << ' ' << *word << ' ' << word + 3 << ' ' << word[6] << '\n';   // cout prints char* as text
    return 0;
}

Output

65
pointer p nter r

The four classic pointer bugs

  • Null / wild pointer dereference – using a pointer that is null or was never initialized: crash or garbage.
  • Dangling pointer – using a pointer after its object is gone (deleted, or a local that went out of scope): undefined behaviour.
  • Memory leak – losing the last pointer to heap memory without deleting it; the memory stays used until the program ends.
  • Double delete – deleting the same memory twice: heap corruption.
#include <iostream>

int* make_counter() {
    // int local = 0; return &local;     WRONG: local dies here → dangling pointer
    return new int(0);                   // heap memory outlives the function
}

int main() {
    int* c = make_counter();
    ++*c;
    std::cout << *c << '\n';
    delete c;
    c = nullptr;                         // after delete, null the pointer...
    delete c;                            // ...then a second delete is harmless (deleting nullptr does nothing)
    if (!c) std::cout << "pointer is null, no dangling access\n";
    return 0;
}

Output

1
pointer is null, no dangling access

RAII and smart pointers

The professional answer to all four bugs is RAII (Resource Acquisition Is Initialization): give each resource an owner object whose destructor releases it. When the owner goes out of scope – normally, by return or by exception – the memory is freed automatically. std::unique_ptr and std::shared_ptr (covered fully in the Smart Pointers topic) are ready-made RAII owners; std::vector and std::string are RAII owners for arrays and text. In modern code, raw new/delete rarely appears outside such classes.

#include <iostream>
#include <memory>

struct Buffer {
    int* data;
    int size;
    explicit Buffer(int n) : data(new int[n]{}), size(n) { std::cout << "allocate " << n << '\n'; }
    ~Buffer() { delete[] data; std::cout << "free " << size << '\n'; }   // destructor releases automatically
    Buffer(const Buffer&) = delete;                                      // no accidental copies
    Buffer& operator=(const Buffer&) = delete;
};

int main() {
    {
        Buffer b(4);
        b.data[0] = 9;
        std::cout << "using " << b.data[0] << '\n';
    }                                                  // b goes out of scope → destructor runs
    auto p = std::make_unique<int>(55);                // smart pointer: deletes itself
    auto arr = std::make_unique<int[]>(3);
    arr[2] = *p;
    std::cout << arr[2] << '\n';
    return 0;
}                                                      // p and arr are freed here

Output

allocate 4
using 9
free 4
55

Pointers vs references

PointerReference
Can be nullyes (nullptr)no – must refer to an object
Can be re-seatedyesno – bound once
Syntax*p, p->mused like the object itself
Arithmeticyesno
Typical useoptional objects, arrays, ownership, data structuresparameters, aliases, return of members

Common mistakes

  • Uninitialized pointers – write int* p = nullptr;.
  • Returning the address of a local variable.
  • delete instead of delete[] for arrays (and vice versa).
  • Forgetting to free on early returns or exceptions – use RAII.
  • Using a pointer after delete – set it to nullptr or let it go out of scope.
  • int* a, b; – b is an int, not a pointer.
  • Pointer arithmetic beyond the array (other than one past the end).

Key points to remember

  • &x is an address; *p is the object at an address; p->m is (*p).m.
  • p + n moves n elements; a[i] == *(a + i).
  • const int* protects the value; int* const protects the pointer.
  • new pairs with delete, new[] with delete[]; deleting nullptr is safe.
  • Prefer RAII: std::vector, std::string, std::unique_ptr, std::shared_ptr.

Frequently asked questions

What is the difference between NULL and nullptr?

NULL is a macro that is usually 0, an integer, so it can pick the wrong overload. nullptr (C++11) has its own type, std::nullptr_t, and converts only to pointer types.

Where is memory from new allocated?

On the free store (heap). It stays allocated until delete is called, independent of scope.

Should I still use raw pointers in modern C++?

Raw pointers are fine as non-owning observers (a pointer to an object someone else owns). For ownership use smart pointers or containers, so memory is released automatically.

Where can I learn more?

Read C++ Smart Pointers and C++ References, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links