█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/C/C and Security
50 minAdvanced

C and Security

After this lesson, you will be able to: Recognise buffer overflows, format string vulnerabilities, unsafe-function alternatives.

Half of CVEs in the wild are C memory bugs. Knowing what causes them = writing safer code.

Prerequisites:Compilation and Linking

Buffer overflows in two paragraphs

C arrays don't bounds-check. A `char buf[64]` overflow from input writes past the buffer into adjacent memory (stack-smashing). On the stack, that adjacent memory often contains the function's RETURN ADDRESS, overwrite it = redirect execution to attacker code. Modern mitigations: stack canaries (-fstack-protector), ASLR, NX bit. But the vuln class still ships regularly. Always write bounds-checked code.

Format string vulnerability

User-controlled format strings = read/write arbitrary memory.

tsx
// VULNERABLE
char buf[256];
fgets(buf, sizeof(buf), stdin);
printf(buf); // attacker controls format string!
// Attacker types: "%s%s%s%s%s", reads adjacent stack memory; can crash or leak.
// Worse: %n writes to memory the attacker chooses.
// SAFE
printf("%s", buf); // user input as data, not format

Unsafe-function cheat sheet

strcpy → strncpy + manual null-terminate (or strlcpy on BSD/macOS). strcat → strncat. sprintf → snprintf. gets → fgets. scanf("%s") → scanf("%255s", ...) with width, or fgets. Better: use C++ std::string / std::vector, or migrate to Rust.

Mitigations every project should enable

-Wall -Wextra -Wformat (catches format string mismatches). -fstack-protector-strong (stack canary). -D_FORTIFY_SOURCE=2 (compile-time + run-time checks on stdlib calls). -fsanitize=address,undefined for tests. Modern OS provides ASLR + NX automatically, keep them on.

Common mistakes only experienced C devs avoid

User input through printf format. Trusting the size of user input. Always cap. Stripping warnings to ship. Warnings ARE the security review. Skipping ASan in CI. Memory bugs hide for years; ASan finds them.

Quick Check

What's wrong with `printf(userInput);`?

Pick the security bug.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Compilation and Linking
Back to C
Intro to Systems Programming→