These are the notes for Cybersecurity Fundamentals (defensive), episode 52. Episode 51 ended on a bug that no input check can see: a C program writing 20 bytes into a box that holds 16. To understand bugs like that, we first need to see how a running program uses memory: where its code and data live, how function calls keep track of where to return, how the heap works, and what "undefined behaviour" means. We start from zero. You don't need to know C already: every line is explained, and every term is defined the first time it appears. The Glossary at the end defines them all again.
Asha, the canteen and every value are made up. Nothing outside the machine is contacted. Every sample was run on 12 Nov 2026 in the SyntaxPilot compiler (gcc 13.3 with -O2, Python 3, OpenJDK 21), and every output below is copied from a real run. Addresses are different on every run (that's ASLR, episode 55), so your numbers will not match ours; the pattern will.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A function can't change Asha's marks | memory, bytes, addresses, pointers (& and *) |
| Where does a program keep everything? | process memory layout: text, rodata, data, BSS, heap, stack |
| How does a function know where to go back? | stack frames, local variables, the return address |
| A receipt label disappears after a function returns | dangling pointers, the heap, malloc and free |
| 100 labels are never given back | memory leaks |
| A function calls itself forever | recursion, base case, stack overflow, segmentation fault |
| A loop reads box 5 of an array of 4, with no error | undefined behaviour, bounds checking |
| The same loop in Python and Java | memory-safe vs memory-unsafe languages |
| How big is the problem? | why about 70% of severe bugs are memory-safety bugs |
Problem 1: memory, addresses and pointers
Real-life example: a very long street of tiny houses, each with a unique house number. A slip of paper with a house number on it is not the house; it only says where the house is.
- Memory (RAM, random access memory) is where a running program keeps everything it is working on. Think of it as millions of numbered boxes.
- A bit is a single 0 or 1. A byte is 8 bits, enough to store one number from 0 to 255. Each box in memory holds one byte.
- An address is the number of a box. Programs print addresses in hexadecimal (base 16: digits 0-9 then a-f), with
0xin front. Example:0x7ffcf749ac24. - A variable is a named box (or a few boxes together) that holds a value. In C,
int asha = 90;makes a variable of typeint(a whole number, 4 bytes here) holding 90. - A pointer is a variable whose value is an address.
int *pmeans "p holds the address of an int". &xmeans the address of x.*pmeans go to the address in p and use the box there (this is called dereferencing).- Pass by value: C gives a function a copy of each argument. Changing the copy doesn't change the original.
Demo 1: a bonus that doesn't stick
// A program's variables live at numbered places in memory.
#include <stdio.h>
void add_bonus_v1(int marks) { // gets a COPY
marks = marks + 5;
}
void add_bonus_v2(int *marks) { // gets the ADDRESS
*marks = *marks + 5; // go there, change it
}
int main(void) {
int asha = 90;
printf("asha lives at address %p\n", (void *)&asha);
printf("size of an int: %zu bytes\n", sizeof asha);
add_bonus_v1(asha);
printf("after v1: %d\n", asha);
int *p = &asha; // p holds asha's address
add_bonus_v2(p);
printf("after v2: %d\n", asha);
printf("p = %p, *p = %d\n", (void *)p, *p);
return 0;
}
Real output (your address will differ):
asha lives at address 0x7fff91fb3954
size of an int: 4 bytes
after v1: 90
after v2: 95
p = 0x7fff91fb3954, *p = 95
What happened, line by line:
printfprints formatted text.%pprints an address,%da whole number,%zua size.sizeof ashais the number of bytesashatakes: 4.add_bonus_v1(asha)gave the function a copy of 90. It added 5 to its copy and threw it away, so Asha still has 90.add_bonus_v2(p)gave the function the address of Asha's box.*marks = *marks + 5went to that box and changed it, so Asha now has 95.pholds exactly the address we printed forasha.
You just invented pointers: when a function must change the caller's data, give it the address.
Problem 2: the memory layout of a process
Real-life example: a school building. The printed rule book (nobody edits it), the office register (facts everyone shares), storerooms you request and return, and the canteen's stack of trays.
- A process is a running program: its code plus its own private memory, given to it by the operating system (OS: the software, like Linux or Windows, that runs programs and shares the hardware between them).
- The process's memory is split into areas (often called segments or sections):
| Area | What lives there | Example from the demo | Can it change? |
|---|---|---|---|
| text | the program's machine code (the CPU's instructions) | the function greet |
read-only, executable |
| rodata (read-only data) | constants | const char motto[] |
read-only |
| data | global variables with a starting value | int school_code = 4512; |
yes |
| BSS | global variables with no starting value, filled with zeros | int visitors; |
yes |
| heap | memory asked for while the program runs | malloc(100 * sizeof(int)) |
yes, until free |
| stack | local variables and function call bookkeeping | int marks = 90; inside main |
yes, until the function returns |
- A global variable is declared outside every function, so every function can use it. A local variable is declared inside a function and exists only while that function runs.
constmeans the value can't be changed after it's set.- BSS is an old name ("block started by symbol"). What matters: globals with no value go there, and the OS sets them to 0.
Demo 2: printing the map
// Where does each kind of data live? Print the addresses.
#include <stdio.h>
#include <stdlib.h>
int school_code = 4512; // global, has a value -> data
int visitors; // global, no value -> BSS
const char motto[] = "Learn by doing"; // read-only data
void greet(void) { } // machine code -> text
int main(void) {
int marks = 90; // local -> stack
int *report = malloc(100 * sizeof(int)); // asked for -> heap
printf("text (code) : %p\n", (void *)greet);
printf("rodata (const) : %p\n", (void *)motto);
printf("data (global) : %p\n", (void *)&school_code);
printf("bss (zeroed) : %p value %d\n", (void *)&visitors, visitors);
printf("heap (malloc) : %p\n", (void *)report);
printf("stack (local) : %p\n", (void *)&marks);
free(report); // give the heap back
return 0;
}
Real output (one run):
text (code) : 0x55a4399fd2a0
rodata (const) : 0x55a4399fe090
data (global) : 0x55a439a00010
bss (zeroed) : 0x55a439a00018 value 0
heap (malloc) : 0x55a46973a2a0
stack (local) : 0x7ffcf4ef2114
- text, rodata, data and BSS are close together at low addresses (
0x55...). - The heap is a little higher. The stack is far away, near the top (
0x7ff...). - Run it again and every address changes. The OS shuffles the areas on each run so an attacker can't predict them. That's ASLR (address space layout randomisation), covered in episode 55.
low addresses high addresses
| text | rodata | data | BSS | heap → ...free... ← stack |
The heap grows up (toward higher addresses) as you allocate; the stack grows down with every call. Security bugs happen when data meant for one box spills onto its neighbour.
Problem 3: stack frames and the return address
Real-life example: in a canteen app main calls take_order, which calls serve. When serve is done, the computer must jump back to the exact spot inside take_order. So each call leaves a note: "when you're done, come back HERE".
- A function call jumps to another function's code. When the function returns, execution continues just after the call.
- The return address is that note: the address of the instruction right after the call, in the caller.
- A stack frame is the tray one call puts on the stack: its local variables, its return address, and a little bookkeeping (saved registers; a register is a tiny, very fast storage slot inside the CPU). When the call returns, its frame is removed.
- The stack is last-in, first-out, like trays: the newest frame is always on top and removed first.
- An inline function is one the compiler copies into its caller instead of really calling it.
__attribute__((noinline))forbids that, so we see real frames.volatiletells the compiler to really keep a variable in memory.
Demo 3: watching the frames
// Each function call gets its own frame on the stack.
#include <stdio.h>
#define NOINLINE __attribute__((noinline)) // keep each call real
NOINLINE void serve(int table) {
volatile int bill = table * 100; // serve's local
printf(" serve frame : bill at %p\n", (void *)&bill);
printf(" serve will return to %p\n", __builtin_return_address(0));
}
NOINLINE void take_order(int table) {
volatile int items = 3; // take_order's local
printf(" order frame : items at %p\n", (void *)&items);
serve(table);
printf(" back in take_order, items = %d\n", items);
}
int main(void) {
volatile int table = 7;
printf(" main frame : table at %p\n", (void *)&table);
printf(" take_order code starts at %p\n", (void *)take_order);
take_order(table);
return 0;
}
Real output:
main frame : table at 0x7ffd4bfba2b4
take_order code starts at 0x564ffd03b260
order frame : items at 0x7ffd4bfba294
serve frame : bill at 0x7ffd4bfba274
serve will return to 0x564ffd03b2a0
back in take_order, items = 3
- Each frame is 32 bytes (
0x20) lower than its caller's: the stack grows down. serve will return to ...2a0, an address just after wheretake_order's code starts (...260): insidetake_order, right after the call toserve.__builtin_return_address(0)is a GCC feature that gives the current function's return address. It's only for learning and debugging here.
Why defenders care: a function's local arrays and its return address sit in the same frame. If a program writes past the end of a local array, it can overwrite data the program relies on to know where to go next, and the program misbehaves or crashes. Episode 53 names these bug classes, episode 54 shows how to write C that avoids them, and episode 55 shows the protections built into compilers and operating systems.
Problem 4: the heap, malloc and free
Real-life example: a function writes a receipt label into a local array and hands back its address. But when the function returns, its tray is removed, and the label was on that tray.
- A buffer is a block of memory that holds data, like a
char text[32]array of 32 characters. snprintf(buf, size, ...)prints formatted text into a buffer and never writes more thansizebytes (including the final\0that marks the end of a C string).- A dangling pointer is a pointer to memory that is no longer valid, like the address of a local after its function returned.
malloc(n)(memory allocate) asks fornbytes on the heap and returns a pointer to them, or NULL (a special pointer value meaning "nothing") if there is no memory left. Heap memory stays valid until you give it back withfree(p).- A compiler warning is a message from the compiler saying "this compiles, but it's probably a bug". Always read them.
Demo 4: returning a local
// Make a receipt label in a function and hand it back.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *label_v1(int table) { // the label lives in v1's frame
char text[32];
snprintf(text, sizeof text, "Table %d: paid", table);
return text; // address of a local!
}
char *label_v2(int table) { // the label lives on the heap
char *text = malloc(32);
if (text == NULL) return NULL; // malloc can fail
snprintf(text, 32, "Table %d: paid", table);
return text; // caller must free() it
}
int main(void) {
char *b = label_v2(7);
printf("v2: %s\n", b);
free(b); // give it back, once
char *a = label_v1(7);
printf("v1: %s\n", a);
return 0;
}
Real output:
main.c: In function 'label_v1':
main.c:9:12: warning: function returns address of local variable [-Wreturn-local-addr]
9 | return text; // address of a local!
| ^~~~
v2: Table 7: paid
v1: (null)
- GCC warned:
function returns address of local variable [-Wreturn-local-addr]. v2printed the label correctly: heap memory survives the return.v1printed(null): using a frame after it's gone is undefined behaviour, so GCC was allowed to do anything, and it returned a null pointer. Another compiler or setting might print garbage or crash. Never rely on any of these.
The rules of the heap
| Rule | Why |
|---|---|
Check malloc's result for NULL |
it fails when memory runs out |
Every malloc needs exactly one free |
never: a leak; twice: a double free (episode 53) |
Don't use memory after free |
that's use-after-free (episode 53) |
| Decide who owns (must free) each block | the caller, here, after label_v2 |
Demo 5: a hundred labels, a leak
A memory leak is memory that is allocated but never freed. We count blocks ourselves with live.
// 100 tables tonight. Each label is malloc'ed. Who frees it?
#include <stdio.h>
#include <stdlib.h>
int live = 0; // blocks taken, not yet given back
char *label(int table) {
char *text = malloc(32); // heap: lives until free()
if (text == NULL) exit(1);
live++;
snprintf(text, 32, "Table %d: paid", table);
return text;
}
void give_back(char *text) { free(text); live--; }
int main(void) {
for (int t = 1; t <= 100; t++) { // v1: print, forget to free
char *s = label(t);
if (t == 100) printf("v1 last label: %s\n", s);
}
printf("v1 blocks never freed: %d (%d bytes)\n", live, live * 32);
live = 0;
for (int t = 1; t <= 100; t++) { // v2: free each label once
char *s = label(t);
if (t == 100) printf("v2 last label: %s\n", s);
give_back(s);
}
printf("v2 blocks never freed: %d (%d bytes)\n", live, live * 32);
return 0;
}
Real output:
v1 last label: Table 100: paid
v1 blocks never freed: 100 (3200 bytes)
v2 last label: Table 100: paid
v2 blocks never freed: 0 (0 bytes)
A server that leaks a little on every request slowly runs out of memory and crashes. An attacker who can send requests quickly can cause that on purpose: a denial of service (DoS), an attack on availability from episode 2. Tools such as Valgrind find leaks automatically (episode 54).
Problem 5: stack overflow
- Recursion is a function calling itself. A base case is the condition where it stops.
- The stack has a fixed size, 8 MB by default on this Linux machine (
ulimit -sprints8192, in kilobytes). - A stack overflow happens when frames go past the end of the stack.
- A segmentation fault (segfault,
SIGSEGV) is the OS stopping a program that touched memory it isn't allowed to touch.setvbuf(stdout, NULL, _IONBF, 0)turns off output buffering so lines appear before the crash.
Demo 6: frames that never stop
// Stack frames pile up. What if they never stop?
#include <stdio.h>
int depth = 0;
int count_down(int n) {
volatile char frame_fill[1024]; // 1 KB of locals per call
frame_fill[0] = (char)n;
depth++;
if (depth % 2000 == 0)
printf("depth %d, frame at %p\n", depth, (void *)frame_fill);
return count_down(n - 1) + frame_fill[0]; // forgot the base case
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0); // print at once, before a crash
count_down(10);
return 0;
}
Real output:
depth 2000, frame at 0x7ffc5460db70
depth 4000, frame at 0x7ffc5440a170
depth 6000, frame at 0x7ffc54206770
Segmentation fault
Each 2,000 calls the frame is about 2 MB lower (each frame holds 1 KB of locals plus bookkeeping), until the program runs off the stack. A crash is the lucky outcome because everyone notices. Silent bugs are worse.
Problem 6: undefined behaviour and bounds checking
- An array is a row of boxes of the same type.
int marks[4]has boxesmarks[0]tomarks[3]; the number in brackets is the index. - Bounds checking means checking that an index is inside the array before using it. C does not do this.
- Undefined behaviour (UB) is what the C standard calls an operation it makes no promise about, like reading outside an array. The program might print garbage, crash, or seem to work, and the compiler may assume it never happens.
- An off-by-one error is a loop or size that is one too big or too small, like
i <= 4instead ofi < 4.
Demo 7: one box too far, in C
// Four students' marks. The loop runs one step too far.
#include <stdio.h>
int main(void) {
int marks[4] = {90, 85, 77, 68};
int total = 0;
for (int i = 0; i <= 4; i++) { // <= : one step too far
printf("marks[%d] = %d\n", i, marks[i]);
total += marks[i];
}
printf("total = %d\n", total);
return 0;
}
Real output:
main.c: In function 'main':
main.c:8:9: warning: iteration 4 invokes undefined behavior [-Waggressive-loop-optimizations]
8 | printf("marks[%d] = %d\n", i, marks[i]);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.c:7:23: note: within this loop
7 | for (int i = 0; i <= 4; i++) { // <= : one step too far
| ~~^~~~
marks[0] = 90
marks[1] = 85
marks[2] = 77
marks[3] = 68
marks[4] = 0
total = 320
GCC warned iteration 4 invokes undefined behavior, but the program still ran. marks[4] read whatever happened to be next in memory (0 this time), and the total silently included it. C computed start address + 4 × 4 bytes and read there. If the program had written there, it would have changed some other variable.
Demo 8: the same loop in Python
# The same off-by-one loop in Python, a memory-safe language.
marks = [90, 85, 77, 68]
total = 0
for i in range(5): # one step too far, again
print(f"marks[{i}] = {marks[i]}")
total += marks[i]
print("total =", total)
Real output:
marks[0] = 90
marks[1] = 85
marks[2] = 77
marks[3] = 68
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(f"marks[{i}] = {marks[i]}")
~~~~~^^^
IndexError: list index out of range
Demo 9: and in Java
// And in Java: every array access is checked.
public class Main {
public static void main(String[] args) {
int[] marks = {90, 85, 77, 68};
int total = 0;
for (int i = 0; i <= 4; i++) { // one step too far
System.out.println("marks[" + i + "] = " + marks[i]);
total += marks[i];
}
System.out.println("total = " + total);
}
}
Real output:
marks[0] = 90
marks[1] = 85
marks[2] = 77
marks[3] = 68
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at Main.main(Main.java:7)
Python and Java check every index first and stop with an error before touching memory.
Memory-safe vs memory-unsafe languages
| Memory-unsafe: C, C++ | Memory-safe: Python, Java, Go, Rust, C# | |
|---|---|---|
| Out-of-bounds index | reads or writes whatever is there (UB) | an error or exception |
| Freeing memory | by hand: leaks, double free, use-after-free possible | automatic (a garbage collector) or checked at compile time (Rust) |
| Pointers to dead memory | possible | not possible in normal code |
| Speed and control | maximum, every check is up to you | small cost for the checks |
- A memory-safe language prevents these mistakes by design. A memory-unsafe language leaves them to the programmer.
- A garbage collector (GC) is part of a language's runtime that finds memory no part of the program can reach any more and frees it.
- Rust is memory-safe without a garbage collector: its compiler checks rules about who owns each piece of memory (episode 55).
- Memory-safe languages still need the secure-coding habits of episode 51: SQL injection is possible in any language.
Why about 70% of severe bugs are memory-safety bugs
All from sources fetched on 12 Nov 2026:
| Source | What it says |
|---|---|
| Microsoft Security Response Center blog, "A proactive approach to more secure code", 16 July 2019 | "~70% of the vulnerabilities Microsoft assigns a CVE each year continue to be memory safety issues" |
| Chromium project, "Memory safety" page | "Around 70% of our high severity security bugs are memory unsafety problems (that is, mistakes with C/C++ pointers). Half of those are use-after-free bugs." Based on "912 high or critical severity security bugs since 2015" |
| CISA (with the NSA), "New Guidance Released for Reducing Memory-Related Vulnerabilities", 24 June 2025 | memory-safe languages "offer the most comprehensive mitigation against this class of vulnerabilities" |
A CVE (episode 8) is the public ID of one vulnerability. CISA is the US Cybersecurity and Infrastructure Security Agency; the NSA is the US National Security Agency.
Why so many?
- Operating system kernels, browsers, routers and media software contain huge amounts of C and C++, chosen for speed and control.
- In those languages, one missing check is undefined behaviour.
- These bugs are often silent: wrong data, no error, often no crash.
- Ordinary data sits next to data that controls the program, like the return address.
The defences, in the next three episodes: knowing the bug classes (53), secure coding and checking tools in C and C++ (54), and system mitigations plus memory-safe languages (55).
The whole chain
- A bonus was lost on a copy → addresses and pointers (
&,*). - Where does everything live? → text, rodata, data, BSS, heap, stack.
- How does a call come back? → stack frames and the return address.
- A label vanished with its frame → the heap:
malloc, checkNULL,freeonce. - 100 labels never returned → memory leaks.
- Frames forever → stack overflow, segmentation fault.
- Box 5 of 4 → undefined behaviour; memory-safe languages turn it into a clean error.
Common mistakes (and what they cause)
| Mistake | Real message or result | Why | Fix |
|---|---|---|---|
return text; where text is a local array |
warning: function returns address of local variable [-Wreturn-local-addr], then v1: (null) |
the frame is gone after return | malloc it, or let the caller pass a buffer in |
for (int i = 0; i <= 4; i++) marks[i] on int marks[4] |
warning: iteration 4 invokes undefined behavior [-Waggressive-loop-optimizations], marks[4] = 0 |
valid indexes are 0..3 | i < 4, or loop up to a stored count |
malloc with no free |
v1 blocks never freed: 100 (3200 bytes) |
a memory leak | exactly one free per malloc |
| recursion with no base case | Segmentation fault |
stack overflow | a base case; limit the depth |
| the same off-by-one in Python | IndexError: list index out of range |
Python checks bounds | range(len(marks)) |
| the same off-by-one in Java | java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 |
Java checks bounds | i < marks.length |
| ignoring compiler warnings | the bug ships | warnings are free bug reports | read them; episode 54 makes them errors |
Mini project: a memory map of your own program
Write one C program that:
- has one global with a value, one without, one
conststring and two functions; - prints the address of each, plus a local in
mainand amalloc'ed block; - calls three nested functions, each printing the address of its local;
- frees everything it allocates and checks every
mallocforNULL.
Run it twice and write down which addresses change and which areas stay in the same order. Sketch the map with low addresses on the left.
Practice
1. Print the address of a local in four nested calls.
Solution
// Homework 1: four nested calls, four frames.
#include <stdio.h>
#define NOINLINE __attribute__((noinline))
NOINLINE void d4(void) { volatile int x = 4; printf("d4 local at %p\n", (void *)&x); }
NOINLINE void d3(void) { volatile int x = 3; printf("d3 local at %p\n", (void *)&x); d4(); }
NOINLINE void d2(void) { volatile int x = 2; printf("d2 local at %p\n", (void *)&x); d3(); }
NOINLINE void d1(void) { volatile int x = 1; printf("d1 local at %p\n", (void *)&x); d2(); }
int main(void) { d1(); return 0; }
Real output:
d1 local at 0x7ffcb30186b4
d2 local at 0x7ffcb3018694
d3 local at 0x7ffcb3018674
d4 local at 0x7ffcb3018654
Each frame is 32 bytes lower than the last.
2. Fix label_v1 by letting the caller pass a buffer in.
Solution
// Homework 2: the caller owns the buffer, so nothing dangles.
#include <stdio.h>
void label_v3(int table, char *out, size_t size) {
snprintf(out, size, "Table %d: paid", table); // never more than size
}
int main(void) {
char text[32]; // lives in main's frame
label_v3(7, text, sizeof text);
printf("v3: %s\n", text);
return 0;
}
Real output:
v3: Table 7: paid
The buffer lives in main's frame, which is still there when label_v3 returns. Passing sizeof text lets snprintf stay inside it.
3. Give count_down a base case.
Solution
// Homework 3: count_down with a base case.
#include <stdio.h>
int count_down(int n) {
if (n == 0) return 0; // base case: stop here
printf("%d ", n);
return count_down(n - 1);
}
int main(void) {
count_down(5);
printf("liftoff\n");
return 0;
}
Real output:
5 4 3 2 1 liftoff
4. Why is a silent bug worse than a crash?
Answer
A crash is noticed, reported and fixed. A silent bug keeps running with wrong data: a wrong total, a changed variable, or memory an attacker can influence. Nobody knows it's there until it is misused.
5. In Demo 2, why does visitors print 0 even though we never set it?
Answer
It is a global with no starting value, so it is in BSS, and the OS fills BSS with zeros before the program starts. A local with no value is different: it holds whatever was on the stack before (garbage), and reading it is undefined behaviour.
Quick quiz
int count = 5; // (1)
int total; // (2)
int main(void) {
int day = 3; // (3)
int *p = malloc(8); // (4) what p points to
}
Where does each live? A: data, BSS, stack, heap · B: stack, stack, stack, heap · C: data, data, heap, stack · D: BSS, data, stack, heap
Answer
A. A global with a value is in data, a global with no value is in BSS, a local is on the stack, and malloc'ed memory is on the heap. The pointer p itself is a local, on the stack.
Interview questions
- What is the difference between the stack and the heap? The stack holds local variables and call frames; it's automatic (a frame is removed when its function returns), fast, and limited in size. The heap holds memory you ask for at run time (
malloc/new); it lives until freed (or until the garbage collector frees it). - What is in a stack frame? The function's local variables, the return address, and saved registers and bookkeeping.
- What is a dangling pointer? Give an example. A pointer to memory that's no longer valid: returning the address of a local array, or using a pointer after
free. - What is undefined behaviour, and why is it a security problem? An operation the language standard makes no promise about. The program may silently do the wrong thing, and compilers may optimise assuming it never happens, so the bug can hide and be hard to predict.
- What makes a language memory-safe? It prevents out-of-bounds access, use-after-free and similar mistakes by design: bounds checks, automatic memory management (garbage collection) or compile-time ownership checks (Rust).
- Why do memory-safety bugs make up so much of the CVE count at companies like Microsoft and Google? Huge C/C++ codebases, UB on one missing check, silent failures, and ordinary data stored next to control data like return addresses. Microsoft (2019) and Chromium both report about 70%.
- What is BSS? The area for global (and static) variables with no starting value; the OS sets it to zero.
Glossary
| Term | Meaning, with an example |
|---|---|
| memory (RAM) | where a running program keeps its data; millions of numbered boxes |
| bit | one 0 or 1 |
| byte | 8 bits; one box of memory; a number 0-255 |
| address | the number of a box in memory, e.g. 0x7ffcf749ac24 |
| hexadecimal (hex) | base-16 numbers with digits 0-9 and a-f, written with 0x |
| variable | a named box holding a value: int asha = 90; |
int |
a whole-number type in C, 4 bytes here |
sizeof |
the number of bytes a type or variable takes: sizeof asha is 4 |
| pointer | a variable that holds an address: int *p = &asha; |
& (address-of) |
gives the address of a variable |
* (dereference) |
goes to the address in a pointer and uses that box |
| pass by value | a function gets a copy of each argument |
printf, %p, %d |
prints formatted text; %p an address, %d a whole number |
| process | a running program plus its private memory |
| operating system (OS) | the software that runs programs and shares the hardware, e.g. Linux |
| process memory layout | how a process's memory is divided: text, rodata, data, BSS, heap, stack |
| segment | one area of a process's memory |
| text segment | the machine code; read-only and executable |
| rodata | read-only data: constants such as const char motto[] |
| data segment | global variables with a starting value |
| BSS | global variables with no starting value, set to zero |
| global variable | declared outside every function; visible to all |
| local variable | declared inside a function; exists while it runs |
const |
a value that can't be changed |
| heap | memory requested at run time; lives until freed |
| stack | memory for local variables and calls; last in, first out |
| function call / return | jump into a function / continue after the call |
| stack frame | one call's area on the stack: locals, return address, bookkeeping |
| return address | where execution continues after a function returns |
| register | a tiny, very fast storage slot inside the CPU |
inline (noinline) |
the compiler copying a function into its caller (or being told not to) |
volatile |
tells the compiler to really keep a variable in memory |
| buffer | a block of memory that holds data, e.g. char text[32] |
snprintf |
prints into a buffer, never more than its size |
C string, \0 |
text in C: characters ending with a zero byte |
| dangling pointer | a pointer to memory that is no longer valid |
malloc |
asks for bytes on the heap; returns a pointer or NULL |
free |
gives heap memory back; exactly once per malloc |
| NULL | a special pointer value meaning "points to nothing" |
| memory leak | heap memory allocated and never freed |
| denial of service (DoS) | making a service unavailable, e.g. by exhausting its memory |
| compiler warning | the compiler saying "this compiles but is probably a bug" |
| recursion | a function calling itself |
| base case | the condition where recursion stops |
| stack overflow | frames growing past the end of the stack |
| segmentation fault (SIGSEGV) | the OS stopping a program that touched memory it may not touch |
| array, index | a row of boxes; the number of one box, starting at 0 |
| off-by-one error | a loop or size one too big or small: <= instead of < |
| bounds checking | checking an index is inside the array before using it |
| undefined behaviour (UB) | an operation the C standard makes no promise about |
| garbage value | whatever happened to be left in memory |
| memory-safe language | prevents out-of-bounds and use-after-free by design: Python, Java, Go, Rust, C# |
| memory-unsafe language | leaves memory checks to the programmer: C, C++ |
| garbage collector (GC) | runtime code that frees memory nobody can reach any more |
| Rust | a memory-safe language without a garbage collector; checks ownership at compile time |
| ASLR | address space layout randomisation: addresses change every run (episode 55) |
| CVE | the public ID of one vulnerability (episode 8) |
| use-after-free | using heap memory after it was freed (episode 53) |
| CISA, NSA | US Cybersecurity and Infrastructure Security Agency; US National Security Agency |
Summary
Memory is a long row of numbered bytes, and a pointer holds one of those numbers. A process has text (code), rodata, data and BSS (globals), a heap that grows up, and a stack that grows down. Every function call gets a stack frame holding its locals and the return address, side by side. Heap memory comes from malloc and must be freed exactly once. C does no bounds checking, so mistakes become undefined behaviour, often silently. Memory-safe languages turn the same mistakes into clean errors, which is why Microsoft and the Chromium project both report that about 70% of their serious security bugs are memory-safety bugs, and why CISA and the NSA recommend memory-safe languages. Next episode: memory corruption bug classes.