Loading lessons...
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
| Area | What lives there | Lifetime | Managed by |
|---|---|---|---|
| Static / global | global and static variables | the whole program | the compiler |
| Stack | local variables and function parameters | until the block or function ends | automatic |
| Heap (free store) | objects created with new | until delete is called | the 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.
| Statement | Effect |
|---|---|
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.
#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:
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 1p++ 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 this | Example |
|---|---|
| tell a member apart from a parameter with the same name | this->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 function | register(this); |
Static member functions and friend functions have no this pointer.
#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:
Elder: Vikram (34)
this inside p1 is &p1? 1
value = 355. Problems with Manual Memory Management
Because the programmer controls heap memory, two errors are common.
| Problem | Cause | Result |
|---|---|---|
| Memory leak | memory 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 pointer | memory is deleted but a pointer to it is still used | reading garbage, corrupting other data, or a crash |
| Double delete | the same memory is deleted twice (e.g. two shallow copies) | undefined behaviour, often a crash |
| Mismatched delete | delete used on memory from new[] (or the reverse) | undefined behaviour; destructors may not run for every element |
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.
#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:
Allocation failed: bad_alloc caught6. 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:
- Predictable performance: a collector pauses the program at unpredictable times, which is unacceptable in real-time and system software.
- Deterministic destruction: in C++ the destructor runs at a known moment, so other resources (files, locks, sockets) are released immediately, not "eventually".
- 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.
#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:
allocated 5 ints
a[4] = 16
freed 5 ints
back in mainThe 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 memory | explicit delete, or automatic through destructors |
| objects freed at an unpredictable time | objects destroyed at a known time (end of scope or delete) |
| run-time overhead and pauses | no hidden run-time cost |
| finalisers may never run | destructors always run for local objects |
| prevents most leaks and dangling pointers | the programmer (or RAII classes) must prevent them |
Key points to remember
- Heap objects:
newallocates and constructs,deletedestructs and frees; arrays usenew[]anddelete []. - Use
p->member(or(*p).member) through a pointer to an object. thispoints to the calling object: separates members from parameters, returns*thisfor chaining.- Errors: memory leak, dangling pointer, double delete; failed
newthrowsbad_alloc. - C++ has no garbage collector; it relies on destructors and RAII (and smart pointers in modern C++).
📝 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/deleteforms, and theItemprogram (single object and array) with output. - Q2. What is the
thispointer? Give its uses with a program. (5 Marks) - Write: the definition, the four uses, and the
Personand chainedCounterprogram. - 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
IntArrayexample, 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)