Practice library / More programming languages
Workbook · Medium · 7 hours
C++ Fundamentals
Memory management, pointers, and C++ for understanding binary vulnerabilities.
On this page 12 sections
- ·Chapter 1 — What is C++?
- ·Chapter 2 — Hello World & Setup
- ·Chapter 3 — Variables & Data Types
- ·Chapter 4 — Operators & Control Flow
- ·Chapter 5 — Functions
- ·Chapter 6 — Arrays & Strings
- ·Chapter 7 — Pointers & References
- ·Chapter 8 — Classes & OOP
- ·Chapter 9 — Inheritance
- ·Chapter 10 — Memory Management
- ·Chapter 11 — STL (Standard Template Library)
- ·Chapter 12 — File I/O & Projects
C++ gives low-level memory control and high-level objects in one language. It powers operating systems, browsers, game engines, and most of the security tools that you use on Kali. This workbook covers the parts that matter for a security engineer: pointers, manual memory management, the stack and the heap, classes, the Standard Template Library, and modern smart pointers. The same features that make C++ fast also make it dangerous, because a wrong pointer is a bug, and a bug on the stack is often an exploit. The chapters build from "hello world" up to a small file project, so that you can read a C++ codebase and reason about where its memory lives.
Install: On Linux or Kali, run sudo apt install g++. On Windows, install MinGW or use VS Code with the C++ extension. Compile with g++ -o program file.cpp and run with ./program.
Chapter 1 — What is C++?
C++ was created by Bjarne Stroustrup in 1979 as "C with Classes." It provides low-level memory control and high-level object-oriented programming (OOP). It is used in game engines (Unreal), operating systems, browsers (Chrome), security tools, high-frequency trading, and embedded systems.
Chapter 2 — Hello World & Setup
// Hello World — save as hello.cpp
#include <iostream> // include input/output library
using namespace std; // use std namespace (cout, cin, endl)
int main() {
cout << "Hello, World!" << endl;
return 0; // 0 = success
}
// Compile and run:
g++ -o hello hello.cpp
./hello
# Output: Hello, World!
// Output:
cout << "Hello" << endl; // endl = newline + flush
cout << "Hello\n"; // \n = newline (faster)
cout << 42 << " " << 3.14; // chain with <<
// Input:
int age;
cout << "Enter age: ";
cin >> age;
cout << "You are " << age << " years old." << endl;Chapter 3 — Variables & Data Types
// C++ requires explicit type declarations
int age = 25; // integer (4 bytes)
long big = 9999999; // larger integer (8 bytes)
float f = 3.14f; // 32-bit decimal
double d = 3.14159; // 64-bit decimal (prefer over float)
char c = 'A'; // single character
bool active = true; // true or false
// auto — compiler infers type (C++11):
auto x = 42; // int
auto y = 3.14; // double
auto z = "hello"; // const char*
// Constants:
const double PI = 3.14159265;
constexpr int MAX = 100; // compile-time constant
// String (use #include <string>):
#include <string>
string name = "Uzair";
cout << name.length() << endl; // 5
cout << name.substr(0, 3) << endl; // Uza
cout << name + " Varsaji" << endl; // Uzair Varsaji
name.replace(0, 5, "Ali"); // Ali Varsaji
// Type sizes (may vary by system):
cout << sizeof(int) << endl; // 4 bytes
cout << sizeof(double) << endl; // 8 bytes
Chapter 4 — Operators & Control Flow
// Same operators as Java — focus on differences:
int a = 10, b = 3;
cout << a / b << endl; // 3 (integer division!)
cout << a % b << endl; // 1
// if/else (identical to Java):
if (a > b) { cout << "a is bigger"; }
else { cout << "b is bigger"; }
// for loop:
for (int i = 0; i < 5; i++) {
cout << i << " ";
} // 0 1 2 3 4
// Range-based for loop (C++11):
int nums[] = {1, 2, 3, 4, 5};
for (int n : nums) {
cout << n << " ";
}
// while / do-while:
int count = 0;
while (count < 3) { cout << count++ << " "; }
// switch:
int choice = 2;
switch (choice) {
case 1: cout << "One"; break;
case 2: cout << "Two"; break;
case 3: cout << "Three"; break;
default: cout << "Other";
}Chapter 5 — Functions
// Function must be declared before it's called (or use prototype):
int add(int a, int b) {
return a + b;
}
// Function prototype (declare before main, define after):
double area(double r);
int main() {
cout << add(3, 4) << endl; // 7
cout << area(5.0) << endl; // 78.5398
return 0;
}
double area(double r) {
return 3.14159 * r * r;
}
// Default arguments:
void greet(string name = "stranger") {
cout << "Hello, " << name << "!" << endl;
}
greet(); // Hello, stranger!
greet("Uzair"); // Hello, Uzair!
// Function overloading:
int multiply(int a, int b) { return a * b; }
double multiply(double a, double b) { return a * b; }
// Pass by reference (modify original):
void doubleIt(int &x) { x *= 2; }
int n = 5;
doubleIt(n);
cout << n; // 10
// Lambda (C++11):
auto square = [](int x) { return x * x; };
cout << square(5); // 25Chapter 6 — Arrays & Strings
// C-style arrays:
int nums[5] = {1, 2, 3, 4, 5};
cout << nums[0]; // 1
// Size: sizeof(nums)/sizeof(nums[0]) = 5
// std::array (C++11, safer):
#include <array>
array<int, 5> a = {10, 20, 30, 40, 50};
cout << a[2] << endl; // 30
cout << a.size() << endl; // 5
cout << a.at(2) << endl; // 30 (bounds-checked)
// 2D array:
int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
cout << matrix[1][2]; // 6
// Strings (#include <string>):
string s = "Hello, World!";
cout << s.length(); // 13
cout << s[0]; // H
cout << s.find("World"); // 7 (position)
s.append(" How are you?");
cout << s.substr(7, 5); // World
cout << (s == "Hello") ; // 0 (false)
// Convert:
int n = stoi("42"); // string to int
string ns = to_string(42); // int to stringChapter 7 — Pointers & References
// Pointers — the most powerful (and dangerous) feature of C++
// & = address-of operator:
int x = 42;
cout << &x; // prints memory address like 0x7ffee4...
// Pointer = variable that stores a memory address:
int *ptr = &x; // ptr holds address of x
cout << ptr; // the address
cout << *ptr; // 42 (dereference — get the value)
*ptr = 100; // change x through the pointer
cout << x; // 100
// Null pointer (C++11):
int *nullPtr = nullptr; // points to nothing
if (nullPtr == nullptr) cout << "Pointer is null!";
// Pointer arithmetic:
int arr[] = {10, 20, 30};
int *p = arr; // points to first element
cout << *p; // 10
p++; // move to next element
cout << *p; // 20
// References — alias for a variable (safer than pointers):
int y = 10;
int &ref = y; // ref IS y (same memory)
ref = 20;
cout << y; // 20
// Pass by pointer (modify original):
void increment(int *n) { (*n)++; }
int val = 5;
increment(&val);
cout << val; // 6Chapter 8 — Classes & OOP
class BankAccount {
private:
string owner;
double balance;
public:
// Constructor:
BankAccount(string owner, double initial = 0.0) {
this->owner = owner;
this->balance = initial;
}
// Destructor (cleanup when object is destroyed):
~BankAccount() {
cout << "Account for " << owner << " closed." << endl;
}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() const { return balance; }
void display() const {
cout << owner << ": £" << balance << endl;
}
};
int main() {
BankAccount acc("Uzair", 1000.0);
acc.deposit(500.0);
acc.withdraw(200.0);
acc.display(); // Uzair: £1300
return 0;
}Chapter 9 — Inheritance
// Base class:
class Shape {
protected:
string colour;
public:
Shape(string c) : colour(c) {}
virtual double area() const = 0; // pure virtual = must override
virtual void display() const {
cout << "Colour: " << colour << ", Area: " << area() << endl;
}
};
// Derived classes:
class Circle : public Shape {
double radius;
public:
Circle(double r, string c) : Shape(c), radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double w, double h, string c) : Shape(c), w(w), h(h) {}
double area() const override { return w * h; }
};
int main() {
Shape* shapes[] = {
new Circle(5, "red"),
new Rectangle(4, 6, "blue")
};
for (Shape* s : shapes) {
s->display();
delete s; // free memory!
}
}Chapter 10 — Memory Management
// Stack vs Heap:
// Stack: automatic, fast, limited size, freed when out of scope
// Heap: manual, slower, large, YOU must free it
// new = allocate on heap, delete = free:
int *p = new int(42); // allocate int on heap
cout << *p; // 42
delete p; // FREE! If you forget: memory leak
p = nullptr; // good practice after delete
// Array on heap:
int *arr = new int[10];
for (int i = 0; i < 10; i++) arr[i] = i;
delete[] arr; // use delete[] for arrays!
// Smart pointers (C++11) — auto-delete, NO manual delete needed:
#include <memory>
unique_ptr<int> up = make_unique<int>(42);
cout << *up; // 42 — freed automatically when out of scope
shared_ptr<int> sp1 = make_shared<int>(100);
shared_ptr<int> sp2 = sp1; // both point to same memory
// freed when BOTH go out of scope (ref count = 0)Chapter 11 — STL (Standard Template Library)
#include <vector>
#include <map>
#include <set>
#include <algorithm>
// vector — dynamic array (most used container):
vector<int> v = {3, 1, 4, 1, 5, 9};
v.push_back(2);
v.pop_back();
cout << v.size(); // 6
cout << v[0]; // 3
sort(v.begin(), v.end()); // sort in place
for (int n : v) cout << n << " "; // 1 1 3 4 5 9
// map — sorted key-value pairs:
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
cout << scores["Alice"]; // 95
for (auto& [key, val] : scores) {
cout << key << ": " << val << endl;
}
// set — unique sorted values:
set<int> s = {3, 1, 4, 1, 5, 9, 2, 6};
for (int n : s) cout << n << " "; // 1 2 3 4 5 6 9
// Algorithm functions:
vector<int> nums = {5, 2, 8, 1, 9};
int mx = *max_element(nums.begin(), nums.end()); // 9
int mn = *min_element(nums.begin(), nums.end()); // 1
int total = accumulate(nums.begin(), nums.end(), 0); // 25
reverse(nums.begin(), nums.end());
sort(nums.begin(), nums.end(), greater<int>()); // descendingChapter 12 — File I/O & Projects
#include <fstream>
// Write to file:
ofstream outFile("output.txt");
if (outFile.is_open()) {
outFile << "Hello, File!" << endl;
outFile << "Line 2" << endl;
outFile.close();
}
// Read from file:
ifstream inFile("output.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
// PROJECT: Number Guessing Game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
int secret = rand() % 100 + 1;
int guess, attempts = 0;
cout << "Guess the number (1-100)!" << endl;
do {
cout << "Your guess: ";
cin >> guess;
attempts++;
if (guess < secret) cout << "Too low!\n";
else if (guess > secret) cout << "Too high!\n";
else cout << "Correct! Got it in " << attempts << " tries!\n";
} while (guess != secret);
return 0;
}Workbook complete. C++ is demanding but powerful. It is used to build operating system kernels, game engines, and security tools. Next steps: practise on HackerRank, study data structures and algorithms, and explore the Qt framework for GUI applications.
Sign in to track progress and send feedback.