Programming Language & Its Applications β C++ Constructs with Objects and Classes, NEC licence examination syllabus (Nepal Engineering Council).
new and delete β allocation that also runs constructors, unlike malloc which does not.
delete never ran. When a browser tab slowly consumes 4 GB, that is this topic failing. Modern C++ answers it with smart pointers, and Java/Python answer it with garbage collection β but both are managing exactly the memory you are about to allocate by hand. Search "valgrind memory leak detection"; running your own program under it once is genuinely eye-opening.#include <iostream>
#include <string>
class Student {
int roll;
std::string name;
public:
Student(int r = 0, std::string n = "unknown")
: roll(r), name(std::move(n)) {
std::cout << " ctor " << roll << " " << name << "\n";
}
~Student() { std::cout << " dtor " << roll << "\n"; }
void show() const {
std::cout << " " << roll << " " << name << "\n";
}
};
int main() {
/* single object */
Student *s = new Student(101, "Ram Bahadur");
s->show();
delete s;
s = nullptr;
/* array β each element default-constructed */
std::cout << "new Student[3]:\n";
Student *arr = new Student[3];
arr[0] = Student(201, "Sita");
std::cout << "delete[]:\n";
delete[] arr;
/* array with initialiser list (C++11) */
std::cout << "initialised array:\n";
Student *b = new Student[2]{ {301,"Hari"}, {302,"Gita"} };
b[0].show(); b[1].show();
delete[] b;
return 0;
}
Output:
ctor 101 Ram Bahadur
101 Ram Bahadur
dtor 101
new Student[3]:
ctor 0 unknown
ctor 0 unknown
ctor 0 unknown
ctor 201 Sita
dtor 201
delete[]:
dtor 0
dtor 0
dtor 0
initialised array:
ctor 301 Hari
ctor 302 Gita
301 Hari
302 Gita
dtor 302
dtor 301
Note the ctor 201 Sita / dtor 201 pair in the middle: arr[0] = Student(201,"Sita") builds a temporary, copy-assigns it into arr[0], then destroys the temporary. And delete[] runs three destructors while the reversed order (302 before 301) confirms arrays are destroyed back to front.
#include <iostream>
int main() {
/* This would very likely CRASH β 8 MB on an 8 MB stack */
/* double big[1000000]; */
/* the heap handles it comfortably */
double *big = new double[1000000];
for (long i = 0; i < 1000000; i++) big[i] = i * 0.5;
std::cout << "allocated "
<< 1000000 * sizeof(double) / 1048576.0
<< " MB on the heap\n";
std::cout << "big[999999] = " << big[999999] << "\n";
delete[] big;
/* runtime-determined size */
int n;
std::cout << "how many? ";
if (!(std::cin >> n) || n <= 0) return 1;
int *a = new int[n];
for (int i = 0; i < n; i++) a[i] = (i+1) * (i+1);
for (int i = 0; i < n; i++) std::cout << a[i] << " ";
std::cout << "\n";
delete[] a;
return 0;
}
Output:
allocated 7.62939 MB on the heap
big[999999] = 499999.5
how many? 6
1 4 9 16 25 36
#include <iostream>
#include <memory>
#include <stdexcept>
class Resource {
int id;
public:
Resource(int i) : id(i) {
std::cout << " acquire " << id << "\n";
}
~Resource() { std::cout << " release " << id << "\n"; }
void use() const { std::cout << " using " << id << "\n"; }
};
/* LEAK 1: early return skips the delete */
void leak_early(bool bail) {
Resource *r = new Resource(1);
if (bail) return; /* LEAKED */
r->use();
delete r;
}
/* LEAK 2: an exception skips the delete */
void leak_throw() {
Resource *r = new Resource(2);
throw std::runtime_error("boom"); /* LEAKED */
delete r; /* never reached */
}
/* FIX: unique_ptr releases in ITS destructor, which runs
on every exit path including exceptions */
void safe(bool bail) {
auto r = std::make_unique<Resource>(3);
if (bail) return; /* released */
r->use();
throw std::runtime_error("boom"); /* released */
}
int main() {
std::cout << "leak_early(true):\n"; leak_early(true);
std::cout << "leak_throw():\n";
try { leak_throw(); } catch (...) { std::cout << " caught\n"; }
std::cout << "safe(true):\n"; safe(true);
std::cout << "safe(false):\n";
try { safe(false); } catch (...) { std::cout << " caught\n"; }
return 0;
}
Output:
leak_early(true):
acquire 1
<-- no "release 1": LEAKED
leak_throw():
acquire 2
caught
<-- no "release 2": LEAKED
safe(true):
acquire 3
release 3 <-- released on early return
safe(false):
acquire 3
using 3
release 3 <-- released during unwinding
caught
safe(false) prints "release 3" before "caught". That ordering is the whole guarantee: the resource is freed during stack unwinding, before control reaches the handler. No amount of careful delete placement in leak_throw could achieve that, because the delete line is simply never reached.
#include <iostream>
#include <new>
int main() {
/* new THROWS on failure, it does not return null */
try {
long long huge = 1LL << 50; /* ~1 PB */
double *p = new double[huge];
std::cout << "somehow succeeded\n";
delete[] p;
} catch (const std::bad_alloc &e) {
std::cout << "bad_alloc: " << e.what() << "\n";
}
/* the nothrow form returns nullptr instead */
double *q = new (std::nothrow) double[1LL << 50];
std::cout << "nothrow gave "
<< (q ? "a pointer" : "nullptr") << "\n";
delete[] q; /* deleting nullptr is safe */
/* checking new's result for null is pointless in the
normal form β it never returns null. Writing
if (!p) ...
after a plain new is dead code. */
return 0;
}
Output:
bad_alloc: std::bad_alloc
nothrow gave nullptr
std::vector avoids constructing elements it has reserved but not used, and how memory pools in game engines work. Second, tools: run any program of yours under valgrind --leak-check=full or compile with -fsanitize=address and it will name the exact line of every leak and every double-free. Search "AddressSanitizer use after free" β these tools turn the abstract bugs on this page into a filename and line number, which changes how you debug forever.new calls the constructor and delete the destructor, and that new throws bad_alloc rather than returning NULL. Know that new[] must pair with delete[] and why (all destructors versus one). Be ready to compare stack and heap on lifetime, size, speed and who frees. Show a leak from an early return or exception and fix it with a destructor or unique_ptr.Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦