For the Name class without a copy constructor, trace Name a("Ravi"); Name b = a; b.set('D'); a.print(); up to the end of main. Assume new returns address 0x5000. What is printed and what goes wrong?
C++ objects can live on the heap through new and delete. A class owning heap memory must manage it — deep copies, the Rule of Three/Five, no leaks or dangling pointers; smart pointers and Java's garbage collector remove most of that burden.
delete). Forget to return it and you keep paying rent (a leak). Return it but keep using the old key and you walk into someone else's goods (a dangling pointer). Photocopying the key instead of the goods is a shallow copy.new T(args) allocates heap memory and calls the constructor, returning a typed T*; delete p runs the destructor, then frees. Failure throws std::bad_alloc, not NULL.new T[n] must be freed with delete[]; mixing new[] with delete, or malloc with delete, is undefined behaviour.char* member that is a shallow copy: one shared buffer, double delete.unique_ptr: sole owner, move-only. shared_ptr: reference-counted (use_count()). weak_ptr: non-owning, breaks cycles. auto_ptr was removed in C++17.delete, no pointer arithmetic; the garbage collector frees unreachable objects.A running C++ program has several memory regions. The code (text) segment holds machine instructions. The static area holds global variables, static locals and static data members. The stack holds local (automatic) variables and parameters; each function call pushes a frame and each return pops it. The heap, also called the free store, is a large pool from which a program can request memory at any moment and keep it as long as it likes.
| Region | What lives there | Lifetime | Who frees it |
|---|---|---|---|
| Stack | Local (automatic) objects and parameters | Until the enclosing block ends | Automatic (destructor at scope exit) |
| Static area | Globals, static locals, static data members | The whole program run | Automatic, after main returns |
| Heap (free store) | Anything created with new | Until delete is applied | The programmer in C++; the garbage collector in Java |
Shape* that point to circles, rectangles and triangles created on the heap.The new operator computes the size of the type, obtains that much memory from the heap, runs the constructor on it and returns a correctly typed pointer. The delete operator runs the destructor and then returns the memory. For arrays, new T[n] calls the default constructor n times and delete[] p calls n destructors — in reverse order — before freeing the block.
#include <iostream>
#include <string>
using namespace std;
class Plot {
string owner;
double cents;
public:
Plot(string o, double c) : owner(o), cents(c) { cout << "Plot " << owner << " created\n"; }
~Plot() { cout << "Plot " << owner << " released\n"; }
double area() const { return cents; }
};
int main() {
int* n = new int(25); // one int, initialised to 25
Plot* p = new Plot("Asha", 4.5); // allocate + run the constructor
int count = *n / 5; // size decided at run time: 5
double* rates = new double[count]; // array of 5 doubles
for (int i = 0; i < count; i++) rates[i] = 7.0 + i * 0.25;
cout << p->area() << " " << rates[count - 1] << "\n";
delete[] rates; // array form for arrays
delete p; // runs ~Plot, then frees the memory
delete n;
p = nullptr; // good habit: leave no dangling pointer
}#include <iostream>
using namespace std;
class Cell {
static int next;
int id;
public:
Cell() : id(++next) { cout << "C" << id << " "; }
~Cell() { cout << "D" << id << " "; }
};
int Cell::next = 0;
int main() {
Cell* one = new Cell; // C1
Cell* row = new Cell[3]; // C2 C3 C4
delete[] row; // D4 D3 D2 : elements destroyed in reverse order
delete one; // D1
cout << "\n";
}| new / delete (C++ operators) | malloc / free (C library functions) | |
|---|---|---|
| Constructor / destructor | Called automatically | Never called |
| Size | Computed from the type | Given in bytes: malloc(n * sizeof(T)) |
| Result type | Correctly typed T* | void*, needing a cast in C++ |
| On failure | Throws std::bad_alloc (new (std::nothrow) returns nullptr) | Returns NULL |
| Arrays | new T[n] and delete[] p | Same call; size computed by hand |
| Customisable | operator new can be overloaded per class | No |
| Resizing | No direct equivalent — use std::vector | realloc() |
new ↔ delete, new[] ↔ delete[], malloc ↔ free. Any mix is undefined behaviour — with objects, delete on an array typically runs only one destructor and corrupts the heap. delete nullptr is harmless; deleting the same pointer twice is not.Many classes need memory whose size depends on the data: a string class holding a name of any length, a matrix of any size, a growable list. Such a class keeps a pointer member, allocates in its constructor (Balagurusamy calls this a dynamic constructor) and frees in its destructor.
#include <cstring>
class Name {
char* s; // owns a heap buffer
public:
Name(const char* src) { // dynamic constructor
s = new char[strlen(src) + 1]; // exactly enough room, +1 for '\0'
strcpy(s, src);
}
~Name() { delete[] s; } // the matching release
};Tying the buffer's lifetime to the object's lifetime is RAII (Resource Acquisition Is Initialisation): when a Name goes out of scope, its destructor frees the buffer automatically — even if an exception is thrown. The trouble starts when such an object is copied.
If you do not write a copy constructor, the compiler generates one that copies every member as it is. For the pointer s that means copying the address, not the characters. After Name b = a; both objects point to the same buffer — a shallow copy.
#include <iostream>
#include <cstring>
using namespace std;
class Name {
char* s;
public:
Name(const char* src) {
s = new char[strlen(src) + 1];
strcpy(s, src);
}
~Name() { delete[] s; }
void set(char c) { s[0] = c; }
void print() const { cout << s << endl; }
// no copy constructor: the compiler-generated one copies the POINTER only
};
int main() {
Name a("Ravi");
Name b = a; // shallow copy: b.s == a.s
b.set('D'); // changes the shared buffer
a.print(); // prints "Davi" -- a was modified through b!
} // ~b frees the buffer, then ~a frees it AGAIN -> double free| Copy style | a.s | b.s | Buffers on the heap |
|---|---|---|---|
| Shallow (compiler-generated) | 0x5000 | 0x5000 | One buffer "Ravi", shared by both objects |
| Deep (user-written) | 0x5000 | 0x6000 | Two buffers, each holding its own "Ravi" |
Name b = a; (addresses are illustrative)b dies first, a.s points to freed memory while a is still in use.The Rule of Three: if a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost certainly needs all three. The need for one is a sign that the class manages a resource, and all three special functions must agree on how that resource is owned.
#include <iostream>
#include <cstring>
using namespace std;
class Name {
char* s;
public:
Name(const char* src = "") {
s = new char[strlen(src) + 1];
strcpy(s, src);
}
Name(const Name& o) { // 1. copy constructor: deep copy
s = new char[strlen(o.s) + 1];
strcpy(s, o.s);
}
Name& operator=(const Name& o) { // 2. copy assignment
if (this != &o) { // guard against a = a
char* fresh = new char[strlen(o.s) + 1];
strcpy(fresh, o.s); // copy first ...
delete[] s; // ... then release the old buffer
s = fresh;
}
return *this; // allows a = b = c
}
~Name() { delete[] s; } // 3. destructor
void set(char c) { s[0] = c; }
void print() const { cout << s << "\n"; }
};
int main() {
Name a("Ravi");
Name b = a; // copy constructor: b gets its own buffer
b.set('D');
a.print(); // Ravi
b.print(); // Davi
Name c;
c = a; // copy assignment
c.print(); // Ravi
}if (this != &o) — without it, a = a would delete the very buffer it is about to copy from.new throws, the object is still intact.delete[] s; — the object already owned memory, unlike in a copy constructor.a = b = c works.Rule of Five (C++11). Copying a temporary that is about to die anyway is wasteful, so C++11 added the move constructor Name(Name&&) and move assignment operator=(Name&&). They steal the source's buffer and leave the source empty but destructible.
class Name {
char* s;
public:
// ... constructor, copy constructor, copy assignment and destructor as above ...
Name(Name&& o) noexcept : s(o.s) { // move constructor: steal the buffer
o.s = nullptr; // leave the source empty (delete[] nullptr is safe)
}
Name& operator=(Name&& o) noexcept { // move assignment
if (this != &o) { delete[] s; s = o.s; o.s = nullptr; }
return *this;
}
};
// Name b = std::move(a); -> no allocation, no copying; a is now emptyRule of Zero. The best owning class is one you never write: use members that manage themselves — std::string, std::vector, std::unique_ptr — and the compiler-generated special functions are then automatically correct.
| Bug | Typical cause | Effect | Cure |
|---|---|---|---|
| Memory leak | new without delete; overwriting the only pointer; an early return | Memory lost until the program exits; long-running servers slowly run out | Match every new; better, RAII and smart pointers |
| Dangling pointer | Using p after delete p; returning the address of a local | Undefined behaviour: garbage values, crashes, silent corruption | Set p = nullptr after delete; never return &local |
| Double delete | Two shallow copies both delete one buffer | Heap corruption, usually a crash | Deep copy (Rule of Three) or shared ownership |
| Mismatched forms | delete p for memory from new T[n] | Undefined behaviour; destructors skipped | new with delete, new[] with delete[] |
| Wild pointer | int* p; *p = 5; (never initialised) | Writes to a random address | Always initialise pointers (nullptr) |
void leaky() {
for (int i = 0; i < 1000; i++) {
int* buf = new int[1000]; // about 4 KB each time round
buf[0] = i;
} // buf dies here, the memory does not: ~4 MB leaked
}
int* dangling() {
int local = 42;
return &local; // local dies when the function returns
}None of these bugs is reported by the language itself. Tools find them at run time: Valgrind (Linux) and AddressSanitizer (compile with -fsanitize=address) report leaks, use-after-free and double frees with the exact source lines.
Modern C++ (header <memory>) wraps raw pointers in smart pointers whose destructors free the memory. unique_ptr<T> is the sole owner: it cannot be copied, only moved (std::move), and it deletes the object when it dies; create it with make_unique (C++14). shared_ptr<T> allows several owners and keeps a reference count (use_count()); the last owner to die deletes the object; create it with make_shared. weak_ptr<T> observes a shared object without owning it, breaking reference cycles. The old auto_ptr was deprecated in C++11 and removed in C++17.
#include <iostream>
#include <memory>
using namespace std;
struct Report {
Report() { cout << "Report opened\n"; }
~Report() { cout << "Report closed\n"; }
};
int main() {
{
unique_ptr<Report> u = make_unique<Report>(); // sole owner
// unique_ptr<Report> u2 = u; // error: cannot copy
unique_ptr<Report> u2 = std::move(u); // ownership transferred
cout << (u ? "u owns" : "u empty") << "\n";
} // u2 dies -> Report closed
shared_ptr<int> p = make_shared<int>(42);
cout << p.use_count() << "\n"; // 1
{
shared_ptr<int> q = p; // count 2
shared_ptr<int> r = q; // count 3
cout << p.use_count() << "\n"; // 3
} // q and r gone
cout << p.use_count() << " " << *p << "\n"; // 1 42
}Java removes the whole problem class. Every object lives on the heap (normally created with new); variables of class type hold references, which cannot be incremented, cast to integers or pointed at stack variables. There is no delete: the garbage collector reclaims an object once nothing reachable refers to it, so dangling references and double frees cannot occur. Assignment between object variables copies the reference — both names then denote one object — so a real copy needs a copy constructor or clone() (which is shallow by default).
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point(Point other) { this(other.x, other.y); } // a hand-written copy constructor
}
public class Alias {
public static void main(String[] args) {
Point p = new Point(1, 2);
Point q = p; // copies the REFERENCE: one object, two names
q.x = 5;
Point r = new Point(p); // a genuine copy
r.x = 9;
System.out.println(p.x + " " + q.x + " " + r.x);
p = null; // the object is still reachable through q
q = null; // now unreachable: eligible for garbage collection
}
}Try the problem first, then reveal the working one step at a time.
For the Name class without a copy constructor, trace Name a("Ravi"); Name b = a; b.set('D'); a.print(); up to the end of main. Assume new returns address 0x5000. What is printed and what goes wrong?
With class Cell (the constructor prints C and an id from a static counter, the destructor prints D and the id), predict the output of Cell* one = new Cell; Cell* row = new Cell[3]; delete[] row; delete one; and say what would happen with delete row;.
Suppose the self-assignment test is removed and the operator deletes first: delete[] s; s = new char[strlen(o.s) + 1]; strcpy(s, o.s);. What happens on c = c;?
In the Alias program of Section 7, what is printed, and at which statement does the first Point object become eligible for garbage collection?
Find and fix the leak: void report(int n) { char* line = new char[80]; if (n < 0) return; sprintf(line, "%d", n); cout << line; delete[] line; }
What is wrong with int* p = new int(5); int* q = p; delete p; *q = 7; delete q;?
Write the copy constructor and copy assignment operator for class IntArray { int* data; int n; public: IntArray(int size) : data(new int[size]()), n(size) {} ~IntArray() { delete[] data; } int& operator[](int i) { return data[i]; } int size() const { return n; } };
Predict the two numbers printed: auto a = std::make_shared<int>(1); auto b = a; { auto c = b; std::cout << a.use_count(); } b.reset(); std::cout << a.use_count();
Rewrite with a smart pointer so that ~Plot() always runs: Plot* p = new Plot("Asha", 4.5); if (!validate(*p)) return false; save(*p); delete p; return true;
new[] with delete (or new with delete[], or malloc with delete) is undefined behaviour, not merely a leak.delete p; does not change p — it still holds the old address and is now dangling. Assign p = nullptr; yourself (and remember other copies of p still dangle).new never returns NULL on failure; it throws std::bad_alloc. Only new (std::nothrow) returns nullptr, so if (p == NULL) after plain new is dead code.b = a for objects copies the reference; Object.clone() is shallow by default. Arrays behave the same way.null does not free memory immediately; it only makes the object eligible for collection.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
new do that malloc() does not?Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
new operator try to allocate its block?