These are the notes for C episode 30, the final episode of the SyntaxPilot C course. You know C now: variables to pointers, memory, files, data structures, a capstone project and interview questions. A friend asks: "Nice. But what can you actually build with it?" Think of a big railway junction: one station, three tracks. C++ for big applications, embedded for devices, and systems programming for the operating system itself. On each track we hit one real problem, run it, watch the obvious code fail, and see the tool that world gives you to fix it. Then a roadmap, projects to build, and a recap of the whole course.
Every example was compiled with the SyntaxPilot compiler's commands: gcc -O2 -Wno-unused-result main.c -o main -lm for C and g++ -O2 -std=c++17 main.cpp -o main for C++ (gcc / g++ 13.3, glibc 2.39, Linux x86-64), and run with standard output going to a pipe, exactly like the online compiler.
The problem: three roads from one station
| Road | What you build | The new problem you'll meet | The tool that solves it |
|---|---|---|---|
| C++ | applications, games, engines, tools | managing every byte by hand | std::string, std::vector, classes |
| Embedded | firmware for devices | one byte controls many pins | bitwise |=, &= ~, ^=, volatile |
| Systems | operating systems, servers, databases | talking to the OS, many processes | system calls: fork, exec, wait |
Road 1: C++
The problem: a greeting card printer in C
A box of 16 chars holds "Hello, ", and strcat adds the name the user types:
#include <stdio.h>
#include <string.h>
int main() {
char greeting[16] = "Hello, ";
char name[50];
scanf(" %49[^\n]", name);
strcat(greeting, name);
printf("%s\n", greeting);
return 0;
}
Input Aman:
Hello, Aman
Input Venkata Lakshmi:
*** buffer overflow detected ***: terminated
Why. "Hello, " is 7 characters, the name is 15, plus the '\0': 23 bytes into a box of 16. In C every array has a fixed size, and checking it is your job. Here glibc's fortified strcat (enabled by -O2 on Ubuntu) caught the overflow and stopped the program; without it, the extra bytes would silently overwrite other memory.
Real-life example: the kitchen.
| In the kitchen | In code |
|---|---|
| A fixed-size pot: you measure so it won't overflow | C: char name[16], you size and check every buffer |
| A pot that grows as you pour, and never spills | C++: std::string and std::vector grow and free themselves |
| A kitchen helper who warns "there's no fifth plate!" | .at(i) checks the index and stops with a clear error |
The fix: std::string and std::vector
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string greeting = "Hello, ";
greeting += "Venkata Lakshmi";
cout << greeting << "\n";
vector<string> names = {"Sana", "Aman", "Kabir"};
names.push_back("Meera");
sort(names.begin(), names.end());
for (const string &n : names) cout << n << " ";
cout << "\n" << names.size() << " names, no malloc, no free\n";
return 0;
}
Hello, Venkata Lakshmi
Aman Kabir Meera Sana
4 names, no malloc, no free
std::stringis a string that grows as you add to it:+=appends, no size anywhere.std::vectoris the dynamic array you built by hand withreallocand capacity doubling in episode 28.push_backadds one at the end;size()is yourn.sort(from<algorithm>) sorts in one line, likeqsortwithout the comparator boilerplate.- When
greetingandnamesgo out of scope at the end ofmain, they free their own memory. This idea, resources released automatically when an object's lifetime ends, is called RAII.
Checked access: .at()
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> marks = {72, 88, 64};
cout << marks.at(5) << "\n";
return 0;
}
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 5) >= this->size() (which is 3)
In C, marks[5] on a 3-element array reads whatever is in memory there, silently (undefined behaviour). .at(5) checks the index and throws an exception, std::out_of_range, with the exact reason. (marks[5] on a vector is still unchecked, like C.)
The biggest idea: a class guards its data
Real-life example: the bank counter. Your money sits in the vault. You can't walk in and change the number yourself; you ask the cashier to withdraw, deposit or show your balance, and the cashier checks the rules every time.
In C, a struct can't do that. The rule lives in withdraw, but any line can skip it:
#include <stdio.h>
struct Account {
char name[20];
int balance;
};
void withdraw(struct Account *a, int amount) {
if (amount > a->balance) { printf("Not enough money\n"); return; }
a->balance -= amount;
}
int main() {
struct Account asha = {"Asha", 1000};
withdraw(&asha, 5000);
asha.balance = -5000; /* nothing stops this */
printf("%s: Rs %d\n", asha.name, asha.balance);
return 0;
}
Not enough money
Asha: Rs -5000
In C++, a class keeps the data private (only the class's own functions can touch it) and offers public methods (functions inside the class), the cashier's counter. A constructor (Account(string n, int b)) sets up each new object.
#include <iostream>
#include <string>
using namespace std;
class Account {
string name;
int balance;
public:
Account(string n, int b) : name(n), balance(b) {}
void withdraw(int amount) {
if (amount > balance) { cout << "Not enough money\n"; return; }
balance -= amount;
}
void show() { cout << name << ": Rs " << balance << "\n"; }
};
int main() {
Account asha("Asha", 1000);
asha.withdraw(5000);
asha.balance = -5000;
asha.show();
return 0;
}
main.cpp: In function 'int main()':
main.cpp:20:10: error: 'int Account::balance' is private within this context
20 | asha.balance = -5000;
| ^~~~~~~
main.cpp:7:9: note: declared private here
7 | int balance;
| ^~~~~~~
The compiler itself guards the vault. Going through the counter instead (asha.withdraw(300); in place of that line):
Not enough money
Asha: Rs 700
Keeping data and the rules that protect it together in one class is called encapsulation, the heart of object-oriented programming (OOP).
Your C carries straight over
- Same syntax:
if,for,while,switch, functions, pointers,struct. - A
structwith its functions inside becomes a class: data and the code that works on it, together. - The STL (Standard Template Library) gives you
string,vector,map,set,sort,findand much more, ready-made. - Where it's used: game engines, browsers, databases, trading systems, desktop apps, and most competitive programming.
Road 2: embedded
What embedded means
Your washing machine, a car's engine controller, a smartwatch, a TV remote: each has a tiny computer called a microcontroller (for example an Arduino's ATmega328P, an ESP32, an STM32). It runs one C program forever, usually with no screen, no keyboard and often no operating system. That program is called firmware.
A microcontroller controls its pins through registers: special memory locations wired to hardware. A port register is one byte where each bit is one pin: bit = 1 means the pin outputs voltage (LED on), 0 means off.
Real-life example: a switchboard with 8 switches: some lights, a fan, a bell. The everyday job: switch on the fan without touching the lights.
The obvious attempt
On a real board PORTB is a hardware register; here it's a plain byte so we can print it.
#include <stdio.h>
void show(unsigned char port) {
for (int bit = 7; bit >= 0; bit--)
printf("%d", (port >> bit) & 1);
printf("\n");
}
int main() {
unsigned char PORTB = 0x0F; /* lights 0-3 are on */
show(PORTB);
PORTB = (1 << 5); /* switch on the fan */
show(PORTB);
return 0;
}
00001111
00100000
The fan (bit 5) is on, and all four lights went off. = replaces the whole byte: one switch on, every other switch off.
The fix: change one bit, keep the rest (episode 18)
#include <stdio.h>
void show(unsigned char port) {
for (int bit = 7; bit >= 0; bit--)
printf("%d", (port >> bit) & 1);
printf("\n");
}
int main() {
unsigned char PORTB = 0x0F; /* lights 0-3 are on */
show(PORTB);
PORTB |= (1 << 5); /* fan on, lights untouched */
show(PORTB);
PORTB &= ~(1 << 0); /* light 0 off */
show(PORTB);
PORTB ^= (1 << 7); /* toggle the bell */
show(PORTB);
return 0;
}
00001111
00101111
00101110
10101110
| Job | Code | How it works |
|---|---|---|
| Set bit k (on) | reg |= (1 << k); |
OR with a mask that has only bit k: other bits unchanged |
| Clear bit k (off) | reg &= ~(1 << k); |
AND with a mask that has every bit except k |
| Toggle bit k | reg ^= (1 << k); |
XOR flips only bit k |
| Test bit k | if (reg & (1 << k)) |
non-zero when bit k is 1 |
This is exactly the code that blinks an LED on an Arduino or an STM32 board.
On a real chip: addresses and volatile
#define LED_PIN 5
volatile uint8_t *port = (uint8_t *)0x25; /* PORTB on an ATmega328P (Arduino Uno) */
*port |= (1 << LED_PIN);
- The register lives at a fixed address in the chip's datasheet; you point a pointer at it.
volatile(episode 29): the hardware can change the value at any moment, so the compiler must read and write it every time and never keep it in a CPU register or remove "useless" repeated writes.uint8_t(from<stdint.h>) is an unsigned type of exactly 8 bits.- Little RAM (often a few kilobytes), often no OS: no big
malloc, careful with every byte, and pointers and bits are the whole job. - Jobs: automotive, IoT (Internet of Things), medical devices, drones, consumer electronics.
Road 3: systems programming
What systems programming means
Writing the programs that talk to the operating system (or are the operating system): shells, servers, databases, compilers. The Linux kernel, Git, SQLite and the Python interpreter itself are written in C.
A running program is a process. A program asks the operating system to do things through system calls (syscalls): fork, exec, wait, open, read, write.
Real-life example: a restaurant with one cook who takes the order, cooks and bills, one at a time. On Linux the process can clone itself with fork(): the copy, the child process, cooks while the original, the parent, does the billing. fork returns 0 in the child and the child's process id (PID) in the parent. wait makes the parent wait for the child to finish.
The obvious attempt
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
printf("Order received. ");
pid_t pid = fork();
if (pid == 0) {
printf("Child: cooking\n");
return 0;
}
wait(NULL);
printf("Parent: billing\n");
return 0;
}
We printed "Order received." once. Run it:
Order received. Child: cooking
Order received. Parent: billing
Twice!
Why. printf doesn't write at once: it collects text in a buffer in the program's memory (episode 21), and writes it out at a newline (on a terminal), when the buffer fills, or when the program exits. When output goes to a pipe or a file, as in the online compiler, it's fully buffered: even a newline doesn't flush it. fork copies the whole process, buffer included, like photocopying a notepad with a half-written line. Both the child and the parent later flush their own copy.
The fix: fflush before fork
printf("Order received. ");
fflush(stdout);
pid_t pid = fork();
Order received. Child: cooking
Parent: billing
fflush(stdout) writes the buffer out now, so the copy the child gets is empty.
What comes next on this road
execreplaces the current program with another one (execvp("ls", argv)):fork+exec+waitis how every shell runs a command.- Files at the OS level:
open,read,write,close(file descriptors: 0 = stdin, 1 = stdout, 2 = stderr). - Threads (
pthread_create): several flows of execution in one process, sharing memory, so you need locks. - Sockets: network connections, how web servers and databases talk.
- Jobs: operating systems, databases, networking, cloud infrastructure, compilers, security.
The roadmap
| If you want… | Learn next | First project |
|---|---|---|
| C++ and big applications | classes, the STL, then DSA and competitive programming (SyntaxPilot has free courses for all three) | rewrite the student record system with vector |
| Embedded | an Arduino or ESP32 board: blink an LED, read a sensor, talk over UART (a serial port) | a temperature logger |
| Systems | Linux system calls, processes, threads, sockets | your own tiny shell |
| Placements | DSA + CS fundamentals: operating systems, databases, networks (SyntaxPilot's CS fundamentals course) | 150 problems, by topic |
Whatever you pick: build projects (a shell, a tiny HTTP server, a key-value store, a text editor), put each one online with a README, and keep the compiler warnings on (-Wall -Wextra) and the sanitizers ready (episode 26). Projects beat certificates.
Common mistakes (and the real messages)
| Code | What you see | Why | Fix |
|---|---|---|---|
asha.balance = -5000; on a C++ class |
error: 'int Account::balance' is private within this context |
balance is private |
go through a public method: asha.withdraw(300); |
char greeting[16]; strcat(greeting, name); with a long name |
*** buffer overflow detected ***: terminated |
23 bytes into 16 | check the size (strncat, snprintf), or std::string in C++ |
marks.at(5) when marks.size() is 3 |
terminate called after throwing an instance of 'std::out_of_range' |
index 5 >= size 3 | check i < marks.size() |
PORTB = (1 << 5); |
no message: every other pin turns off | = replaces all 8 bits |
PORTB |= (1 << 5); |
printf("Order received. "); fork(); |
no message: the text is printed twice | fork copies the stdout buffer |
fflush(stdout); before fork() |
a hardware register without volatile |
no message: the program works in debug and fails with -O2 |
the compiler caches or removes the reads/writes | declare it volatile |
compiling C++ with gcc main.cpp |
undefined reference to ...std::... link errors |
gcc doesn't link the C++ library |
use g++ |
Mini project: a tiny shell
The heart of every shell: read a command, fork, exec it in the child, wait in the parent.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
char line[100];
while (printf("mysh> "), fflush(stdout), fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\n")] = '\0';
if (strcmp(line, "exit") == 0) break;
if (line[0] == '\0') continue;
char *argv[10];
int argc = 0;
for (char *tok = strtok(line, " "); tok && argc < 9; tok = strtok(NULL, " "))
argv[argc++] = tok;
argv[argc] = NULL;
pid_t pid = fork();
if (pid == 0) {
execvp(argv[0], argv);
perror(argv[0]);
_exit(127);
}
int status;
waitpid(pid, &status, 0);
printf("[exit %d]\n", WEXITSTATUS(status));
}
printf("bye\n");
return 0;
}
Input:
echo hello from the child
ls /nonexistent
nosuchcmd
exit
mysh> hello from the child
[exit 0]
mysh> ls: cannot access '/nonexistent': No such file or directory
[exit 2]
mysh> nosuchcmd: No such file or directory
[exit 127]
mysh> bye
How it works: strcspn finds the newline and cuts it off; strtok splits the line into words; execvp searches PATH for the program and replaces the child with it (it only returns if it failed, so we perror and exit with 127, the shell convention for "command not found"); waitpid waits for that child and WEXITSTATUS gets its exit code. Note the fflush(stdout) after the prompt: the same lesson as today's fork bug. Run it on your own Linux or macOS computer (or WSL on Windows). Extensions: a cd built-in (it must run in the shell itself, with chdir), > redirection with open and dup2, and pipes with pipe.
Practice
- Rewrite the student record system from episode 28 in C++ with
vector, sorted by roll, and print the topper. - Blink an LED: toggle pin 5 four times and print the port each time; then test whether the LED ends on or off.
- What does
reg &= ~(1 << 2)do toreg = 0x0F? (the quiz) - Why does
printf("A\n"); fork();printAonce on a terminal but twice into a file?
Solutions
- C++ student list:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
int roll;
string name;
double marks;
};
int main() {
vector<Student> list = {{103, "Kabir Singh", 64}, {101, "Aman Verma", 72}, {105, "Zoya Ahmed", 91}};
list.push_back({102, "Sana Khan", 88});
sort(list.begin(), list.end(), [](const Student &a, const Student &b) { return a.roll < b.roll; });
for (const Student &s : list)
cout << s.roll << " " << s.name << " " << s.marks << "\n";
auto top = max_element(list.begin(), list.end(), [](const Student &a, const Student &b) { return a.marks < b.marks; });
cout << "Topper: " << top->name << "\n";
return 0;
}
101 Aman Verma 72
102 Sana Khan 88
103 Kabir Singh 64
105 Zoya Ahmed 91
Topper: Zoya Ahmed
No realloc, no free, no fixed name size. The [](...) { ... } is a lambda: a small unnamed function, here the comparator.
- Blink:
#include <stdio.h>
void show(unsigned char port) {
for (int bit = 7; bit >= 0; bit--)
printf("%c", (port >> bit) & 1 ? '#' : '.');
printf("\n");
}
int main() {
unsigned char PORTB = 0;
for (int i = 0; i < 4; i++) {
PORTB ^= (1 << 5); /* toggle the LED on pin 5 */
show(PORTB);
/* on a real board: _delay_ms(500); */
}
if (PORTB & (1 << 5)) printf("LED is on\n");
else printf("LED is off\n");
return 0;
}
..#.....
........
..#.....
........
LED is off
An even number of toggles brings it back to off.
-
~(1 << 2)is11111011, so only bit 2 is cleared:00001111becomes00001011= 8 + 2 + 1 = 11. -
On a terminal, stdout is line buffered: the
\nflushesAbeforefork, so the child's copy of the buffer is empty. Into a file or pipe, stdout is fully buffered:Ais still in the buffer atfork, and both processes flush it.
Quick quiz
unsigned char reg = 0x0F; // 00001111
reg &= ~(1 << 2);
printf("%d\n", reg);
- A.
11 - B.
4 - C.
15 - D.
3
Answer
A: 11. ~(1 << 2) has every bit set except bit 2, so only bit 2 is cleared: 00001011 = 8 + 2 + 1 = 11.
More quick checks:
- What does
fork()return in the child?Answer
0. The parent gets the child's PID, and −1 means fork failed. - Which C++ type replaces your hand-written
reallocarray?Answer
std::vector. - Why must a hardware register be
volatile?Answer
The hardware can change it, so the compiler must not cache it or remove reads and writes.
Interview questions
- What does C++ add to C? What is a class? What is RAII?
std::vectorvs a C array: how doespush_backgrow it? What does.at()do that[]doesn't?- How do you set, clear, toggle and test a single bit? Why not use
=? - What does
volatilemean, and when is it needed? Is it enough for thread safety? (No: use atomics or locks.) - What is a microcontroller? What is firmware? Why is dynamic memory often avoided in embedded code?
- What is a process? What does
forkreturn? What happens to open files and memory afterfork? - Explain
fork+exec+wait. How does a shell runls -l? - Why can output appear twice after
fork? Line buffered vs fully buffered stdout. - What is a system call? Name five.
- Process vs thread?
Glossary
| Term | Meaning | Example |
|---|---|---|
| C++ | A language built on C that adds classes, templates and a big standard library | std::vector<int> |
std::string |
C++ string that grows and frees itself | greeting += name; |
std::vector |
C++ dynamic array: grows with push_back, frees itself |
vector<string> names; |
| STL | Standard Template Library: C++'s ready-made containers and algorithms | sort, map, vector |
| Class | A type that bundles data and the functions that work on it | class Account |
private / public |
Members only the class can use / members anyone can use | int balance is private |
| Method | A function inside a class | asha.withdraw(300) |
| Constructor | The method that sets up a new object | Account(string n, int b) |
| Encapsulation | Keeping data and the rules that protect it together, hiding the data | the bank counter |
| Object-oriented programming (OOP) | Building programs from objects that combine data and behaviour | classes in C++ |
| RAII | Resources are released automatically when the object that owns them goes out of scope | a vector freeing its memory at the end of main |
| Exception | An error object thrown to stop normal flow and report a problem | std::out_of_range |
.at(i) |
Vector element access that checks the index | marks.at(5) throws |
| Lambda | A small unnamed function written inline | [](int a, int b) { return a < b; } |
| Embedded system | A computer built into a device to do one job | a washing machine controller |
| Microcontroller | A small chip with CPU, memory and pins in one package | ATmega328P, ESP32, STM32 |
| Firmware | The program that runs on a microcontroller | an LED blinker |
| Register | A special memory location wired to hardware | PORTB |
| Port / pin | A pin is one electrical connection; a port register controls a group of pins, one bit each | bit 5 of PORTB |
| Bit mask | A number with only the bits you want set | 1 << 5 |
volatile |
The value may change outside the program, so always really read/write it | volatile uint8_t *port |
uint8_t |
An unsigned integer of exactly 8 bits, from <stdint.h> |
a register value |
| Systems programming | Writing software that works directly with the operating system | shells, servers, databases |
| Operating system | The software that manages the hardware and runs programs | Linux |
| Process | A running program with its own memory | each ./main run |
| PID | Process id, the number the OS gives each process | returned by fork to the parent |
| System call | A request from a program to the operating system | fork, write |
fork |
Creates a copy of the current process (the child) | pid_t pid = fork(); |
exec |
Replaces the current process's program with another | execvp("ls", argv) |
wait / waitpid |
Wait for a child process to finish and get its exit status | waitpid(pid, &status, 0) |
| Buffer | Memory where output is collected before it's written | stdout's buffer |
fflush |
Write out a stream's buffer now | fflush(stdout); |
| Line / fully buffered | Flushed at each newline (terminals) / only when full or at exit (pipes, files) | why the fork bug appears in the online compiler |
| Thread | A flow of execution inside a process; threads share memory | pthread_create |
| Socket | An endpoint for a network connection | a web server's listening socket |
| Shell | The program that reads commands and runs them | bash, today's mysh |
The whole course in one recap
| Episodes | You learned |
|---|---|
| 1-4 | compile and run, printf, variables and types, operators, scanf and format specifiers |
| 5-7 | if/else, switch, loops, functions |
| 8-11 | arrays, strings, pointers, pointer arithmetic |
| 12-14 | struct, union, enum, malloc/calloc/realloc/free |
| 15-18 | files, the preprocessor and macros, storage classes, bitwise operators |
| 19-21 | command-line arguments, multi-file programs and headers, debugging with gdb |
| 22-25 | linked lists, stacks and queues, trees, sorting and searching |
| 26-27 | memory bugs and sanitizers, recursion |
| 28-30 | the capstone record system, interview questions, and what's next |
Summary
- C++: a class keeps data
privatebehindpublicmethods (encapsulation), so no line can skip the rules; C makes you size and check every buffer (strcatoverflow); C++'sstd::stringandstd::vectorgrow and free themselves,sortis one line,.at()reports bad indexes withstd::out_of_range. - Embedded: a port register is a byte, one bit per pin;
=changes all of them, so use|=to set,&= ~to clear,^=to toggle, and mark hardware registersvolatile. - Systems: programs talk to the OS through system calls;
forkcopies the whole process, including the unflushed stdout buffer, sofflush(stdout)beforefork.fork+exec+waitis how a shell works. - Pick one road, build one project this month, and put it online.
Next on SyntaxPilot: the C++ Full Course, which starts from exactly where you are now. Thank you for finishing the C course!