Lesson 18 +35 XP

Dynamic Memory Allocation, the this Pointer & C++ Garbage Collection

Dynamic Memory Allocation, the this Pointer & C++ Garbage Collection

Objects do not have to be local variables. They can be created at run time on the free store (heap) with new, and live until they are destroyed with delete. This lesson covers dynamic objects, pointers to objects, the this pointer, and the question every examiner likes: does C++ have garbage collection? (No, and the lesson explains what C++ does instead.)

1. Memory Areas of a Program

AreaWhat lives thereLifetimeManaged by
Static / globalglobal and static variablesthe whole programthe compiler
Stacklocal variables and function parametersuntil the block or function endsautomatic
Heap (free store)objects created with newuntil delete is calledthe programmer

Allocating memory at run time, as the program needs it, is dynamic memory allocation. It is needed when the size or number of objects is known only at run time (a list whose length depends on input, a matrix of user-chosen size).

2. Creating Objects Dynamically

new allocates memory for an object and calls its constructor; delete calls the destructor and frees the memory. This is the key advantage over malloc(), which only allocates raw bytes.

StatementEffect
Item* p = new Item;allocate one object; default constructor runs
Item* p = new Item(5, 9.5);allocate one object; parameterized constructor runs
Item* p = new Item[n];allocate an array of n objects; default constructor runs for each
delete p;destructor runs, memory freed
delete [] p;destructor runs for every element, memory freed

3. Pointers to Objects

A pointer can point to an object, just as it points to an int. Members are accessed with the arrow operator ->, or with (*p).member.

C++
#include <iostream>
using namespace std;

class Item {
    int code;
    float price;

public:
    Item() {
        code = 0;
        price = 0;
    }
    Item(int c, float p) {
        code = c;
        price = p;
        cout << "constructed item " << code << endl;
    }
    ~Item() {
        cout << "destroyed item " << code << endl;
    }
    void set(int c, float p) {
        code = c;
        price = p;
    }
    void show() {
        cout << "code " << code << ", price " << price << endl;
    }
};

int main() {
    Item x(1, 50.0);
    Item* ptr = &x; // pointer to an existing object
    ptr->show();    // arrow operator
    (*ptr).show();  // same thing

    Item* d = new Item(2, 99.5); // a dynamic object
    d->show();
    delete d; // destructor runs now

    int n = 3;
    Item* list = new Item[n]; // array of objects on the heap
    for (int i = 0; i < n; i++) {
        list[i].set(10 + i, 5.5f * (i + 1));
    }
    Item* p = list;
    for (int i = 0; i < n; i++, p++) { // pointer arithmetic moves object by object
        p->show();
    }
    delete[] list; // destructor runs for every element
    cout << "end of main" << endl;
    return 0;
}

Output:

OUTPUT
constructed item 1
code 1, price 50
code 1, price 50
constructed item 2
code 2, price 99.5
destroyed item 2
code 10, price 5.5
code 11, price 11
code 12, price 16.5
destroyed item 12
destroyed item 11
destroyed item 10
end of main
destroyed item 1

p++ advances by sizeof(Item) bytes, so it moves to the next object in the array.

4. The this Pointer

Every non-static member function receives a hidden argument: a pointer to the object that called it. This pointer is called this. When you write price inside a member function, the compiler reads it as this->price.

Use of thisExample
tell a member apart from a parameter with the same namethis->code = code;
return the calling object (for chained calls)return *this;
compare with another object (e.g. self-assignment check)if (this == &other)
pass the current object to another functionregister(this);

Static member functions and friend functions have no this pointer.

C++
#include <iostream>
#include <cstring>
using namespace std;

class Person {
    char name[20];
    int age;

public:
    Person(const char* name, int age) {
        strcpy(this->name, name); // this-> separates the member from the parameter
        this->age = age;
    }
    const Person& older(const Person& x) const {
        if (x.age >= age) {
            return x;
        }
        return *this; // return the calling object
    }
    void show() const {
        cout << name << " (" << age << ")" << endl;
    }
    const Person* address() const {
        return this;
    }
};

class Counter {
    int value;

public:
    Counter() {
        value = 0;
    }
    Counter& add(int n) {
        value = value + n;
        return *this;
    } // enables chaining
    void show() {
        cout << "value = " << value << endl;
    }
};

int main() {
    Person p1("Neha", 29), p2("Vikram", 34);
    Person p3 = p1.older(p2);
    cout << "Elder: ";
    p3.show();
    cout << "this inside p1 is &p1? " << (p1.address() == &p1) << endl;

    Counter c;
    c.add(5).add(10).add(20); // each add() returns the same object
    c.show();
    return 0;
}

Output:

OUTPUT
Elder: Vikram (34)
this inside p1 is &p1? 1
value = 35

5. Problems with Manual Memory Management

Because the programmer controls heap memory, two errors are common.

ProblemCauseResult
Memory leakmemory allocated with new is never deleted (often because the only pointer to it was overwritten or went out of scope)the program's memory use keeps growing; long-running programs can run out of memory
Dangling pointermemory is deleted but a pointer to it is still usedreading garbage, corrupting other data, or a crash
Double deletethe same memory is deleted twice (e.g. two shallow copies)undefined behaviour, often a crash
Mismatched deletedelete used on memory from new[] (or the reverse)undefined behaviour; destructors may not run for every element
C++
void leak() {
    int* p = new int[1000];
    // ... return without delete [] p;  -> 4000 bytes lost on every call
}

void dangling() {
    int* p = new int(5);
    delete p;
    // *p = 10;          // dangling pointer: p still holds the old address
    p = NULL; // good practice: reset the pointer after delete
}

Deleting a null pointer is safe and does nothing, which is why resetting pointers to NULL after delete is good practice.

When new fails

If the heap is exhausted, standard new throws a std::bad_alloc exception (Unit IV). Very old compilers returned 0 instead.

C++
#include <iostream>
#include <new>
using namespace std;

int main() {
    try {
        size_t n = 1000000000; // ask for far more memory than exists
        double* big = new double[n * 50];
        cout << "allocated" << endl;
        delete[] big;
    } catch (bad_alloc&) {
        cout << "Allocation failed: bad_alloc caught" << endl;
    }
    return 0;
}

Output:

OUTPUT
Allocation failed: bad_alloc caught

6. Garbage Collection and C++

Garbage collection (GC) is the automatic reclaiming of memory that a program can no longer reach. Languages such as Java, C# and Python have a garbage collector: the run-time system periodically finds unreachable objects and frees them, so the programmer never calls delete.

Standard C++ has no garbage collector. Memory obtained with new stays allocated until the program calls delete (or the program ends). This was a deliberate design choice:

  1. Predictable performance: a collector pauses the program at unpredictable times, which is unacceptable in real-time and system software.
  2. Deterministic destruction: in C++ the destructor runs at a known moment, so other resources (files, locks, sockets) are released immediately, not "eventually".
  3. Zero overhead: programs that do not need GC do not pay for it.

How C++ manages memory instead: RAII

C++ uses RAII, Resource Acquisition Is Initialisation: a resource is acquired in an object's constructor and released in its destructor. Since destructors of local objects run automatically when they go out of scope, even when an exception is thrown, the resource can never leak.

C++
#include <iostream>
using namespace std;

class IntArray { // owns a heap array (RAII)
    int* data;
    int size;

public:
    IntArray(int n) {
        size = n;
        data = new int[n]; // acquire in the constructor
        cout << "allocated " << n << " ints" << endl;
    }
    ~IntArray() {
        delete[] data; // release in the destructor
        cout << "freed " << size << " ints" << endl;
    }
    int& operator[](int i) {
        return data[i];
    }

private:
    IntArray(const IntArray&); // copying disabled (no shallow copies)
    IntArray& operator=(const IntArray&);
};

void work() {
    IntArray a(5); // no new / delete visible to the user
    for (int i = 0; i < 5; i++) {
        a[i] = i * i;
    }
    cout << "a[4] = " << a[4] << endl;
} // destructor runs here: no leak

int main() {
    work();
    cout << "back in main" << endl;
    return 0;
}

Output:

OUTPUT
allocated 5 ints
a[4] = 16
freed 5 ints
back in main

The standard library is built on RAII: string, vector and the other containers (Unit IV) own their memory and free it in their destructors. Modern C++ (C++11) adds smart pointers (unique_ptr, shared_ptr) that delete automatically; shared_ptr uses reference counting, a simple form of automatic memory management.

Garbage collection (Java, C#)C++ (RAII, manual delete)
automatic; the programmer never frees memoryexplicit delete, or automatic through destructors
objects freed at an unpredictable timeobjects destroyed at a known time (end of scope or delete)
run-time overhead and pausesno hidden run-time cost
finalisers may never rundestructors always run for local objects
prevents most leaks and dangling pointersthe programmer (or RAII classes) must prevent them
💡 Tip

Key points to remember

  • Heap objects: new allocates and constructs, delete destructs and frees; arrays use new[] and delete [].
  • Use p->member (or (*p).member) through a pointer to an object.
  • this points to the calling object: separates members from parameters, returns *this for chaining.
  • Errors: memory leak, dangling pointer, double delete; failed new throws bad_alloc.
  • C++ has no garbage collector; it relies on destructors and RAII (and smart pointers in modern C++).
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain dynamic memory allocation for objects in C++ with a program. (5 Marks)
  • Write: the memory-areas table, the new/delete forms, and the Item program (single object and array) with output.
  • Q2. What is the this pointer? Give its uses with a program. (5 Marks)
  • Write: the definition, the four uses, and the Person and chained Counter program.
  • Q3. Does C++ support garbage collection? How is memory managed in C++? (5 Marks)
  • Write: the definition of GC, "no GC in standard C++" with the three reasons, RAII with the IntArray example, and the comparison table.
  • Q4. What are memory leaks and dangling pointers? (2.5 Marks)
  • Q5. Explain pointers to objects and the arrow operator. (2.5 Marks)