Programming in C
C fundamentals, pointers, memory management, debugging with GDB, and systems programming. Essential for embedded work.
Introduction to C; Compilation Model
Why Learn C in 2026? C is over 50 years old, yet it powers: Operating systems - Linux, Windows kernel, macOS core Embedded systems - from ESP32 to satellites Databases - PostgreSQL, SQLite, Redis...
Why Learn C in 2026?
C is over 50 years old, yet it powers:
- Operating systems - Linux, Windows kernel, macOS core
- Embedded systems - from ESP32 to satellites
- Databases - PostgreSQL, SQLite, Redis
- Compilers - CPython, the JVM itself
- Everything under Python, Ruby, Node.js
Learning C teaches you how memory actually works. Once you understand pointers, you understand why Python is slow, why garbage collection exists, and why Rust was invented.
Hello, World - But Let's Understand What Happens
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
Compile and run:
gcc -o hello hello.c
./hello
But what actually happens?
The Compilation Pipeline
C compilation has four stages:
1. Preprocessing
gcc -E hello.c
Expands:
- #include <stdio.h> inserts the entire stdio.h header (thousands of lines)
- #define PI 3.14 text replacement
- #ifdef DEBUG ... #endif conditional compilation
Output: a single .i file with no more # directives.
2. Compilation
gcc -S hello.i
Translates C to assembly (.s file). Example for int x = a + b:
movl -4(%rbp), %eax # load a
movl -8(%rbp), %edx # load b
addl %edx, %eax # a + b
movl %eax, -12(%rbp) # store to x
This is where the compiler optimizes.
3. Assembly
gcc -c hello.s
Assembles to machine code, producing hello.o (object file).
4. Linking
gcc -o hello hello.o
Links your object file with:
- C runtime library (libc.so)
- Your other object files
- Any libraries you link against (-lm for math)
Output: hello executable.
Types in C
C has a small set of primitive types:
Type | Typical size | Range
----------|--------------|-------
char | 1 byte | -128 to 127
short | 2 bytes | -32,768 to 32,767
int | 4 bytes | +/- 2.1 billion
long | 8 bytes | +/- 9.2 quintillion
float | 4 bytes | ~7 digits precision
double | 8 bytes | ~15 digits precision
void* | 8 bytes | any pointer
Use stdint.h for exact sizes:
#include <stdint.h>
int32_t x = 42; // exactly 32 bits, guaranteed
uint8_t y = 255; // exactly 8 bits, unsigned
Variables and Memory
Every variable lives at a memory address:
int a = 10;
int b = 20;
int c = a + b;
In memory:
Address Value Name
0x7ffe1000 10 a
0x7ffe1004 20 b
0x7ffe1008 30 c
The & operator gives the address:
printf("%p\n", (void*)&a); // prints 0x7ffe1000
The * operator dereferences a pointer:
int *p = &a; // p points to a
printf("%d\n", *p); // prints 10
*p = 42; // changes a to 42
Functions and the Call Stack
int add(int x, int y) {
return x + y;
}
int main(void) {
int result = add(3, 4);
printf("%d\n", result);
return 0;
}
When main calls add:
- The caller pushes arguments onto the stack
- A new stack frame is created for add with room for locals
- add runs, places result in a register
- add returns, stack frame is destroyed
The stack grows downward on most architectures (x86, ARM).
Common Beginner Mistakes
- Forgetting & when calling scanf:
int x;
scanf("%d", &x); // correct
scanf("%d", x); // WRONG - segfault
- Using = instead of ==:
if (x = 5) { ... } // always true; assigns 5 to x
if (x == 5) { ... } // correct
- Buffer overflow:
char buf[10];
strcpy(buf, "Hello, World!"); // overflow! 14 bytes into 10-byte buffer
- Uninitialized variables:
int x;
printf("%d\n", x); // undefined value
- Dangling pointers:
int *p = malloc(sizeof(int));
free(p);
*p = 5; // undefined behavior
Debugging with GDB
gcc -g -o hello hello.c # -g adds debug symbols
gdb ./hello
Inside GDB:
- break main - set breakpoint
- run - start program
- next - step over
- step - step into
- print x - print variable
- bt - backtrace
Valgrind for Memory Bugs
valgrind --leak-check=full ./hello
Detects:
- Memory leaks
- Use of uninitialized values
- Buffer overflows
- Invalid frees
Key Takeaways
- C compilation = preprocess -> compile -> assemble -> link
- Types have fixed sizes; use stdint.h for portability
- Every variable has an address; pointers store addresses
- Stack grows downward; each function call creates a frame
- The 5 most common bugs: missing &, = vs ==, overflow, uninit, dangling
- Always use -Wall -Wextra and Valgrind
Pointers and Memory
Pointer arithmetic, pointers vs arrays, stack vs heap, malloc/free, and common memory bugs (dangling pointers, buffer overflows, memory leaks). Debugging with Valgrind....
Pointer arithmetic, pointers vs arrays, stack vs heap, malloc/free, and common memory bugs (dangling pointers, buffer overflows, memory leaks). Debugging with Valgrind.
Strings and Character Arrays
C strings are null-terminated character arrays. We cover the standard library (strlen, strcpy, strcmp), buffer overflow vulnerabilities, and safe alternatives (strncpy, strlcpy)....
C strings are null-terminated character arrays. We cover the standard library (strlen, strcpy, strcmp), buffer overflow vulnerabilities, and safe alternatives (strncpy, strlcpy).
Structs and Unions
Structs group related data; unions let multiple types share the same memory. We show struct padding, alignment, and the __attribute__((packed)) directive....
Structs group related data; unions let multiple types share the same memory. We show struct padding, alignment, and the __attribute__((packed)) directive.
Function Pointers and Callbacks
Function pointers enable runtime polymorphism in C. We use them to implement callbacks, dispatch tables, and generic data structures like qsort....
Function pointers enable runtime polymorphism in C. We use them to implement callbacks, dispatch tables, and generic data structures like qsort.
๐ Problem Set 1: Pointers and Memory
Q1. Write a function `void swap(int *a, int *b)` that swaps two integers using pointers.
Show Solution
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
Q2. Given `char *s = "Hello";`, what is the value of `*s`, `*(s+1)`, and `*(s+4)`? Explain the difference between `char *s` and `char s[]`.
Show Solution
*s = 'H', *(s+1) = 'e', *(s+4) = 'o'. `char *s` points to a read-only string literal (modifying it is undefined behavior). `char s[]` allocates a mutable array on the stack, and its contents can be changed.
Q3. Find and fix the memory bug: `char *p = malloc(10); strcpy(p, "Hello World"); free(p);`
Show Solution
The bug: `"Hello World"` requires 12 bytes (11 chars + null terminator), but only 10 were allocated. Fix: `char *p = malloc(12);` or use `malloc(strlen("Hello World") + 1);`.
๐ฏ Midterm 1: Pointers, Memory, Strings
Q1. Write a function `int count_words(const char *s)` that counts the number of space-separated words in a string.
Show Solution
int count_words(const char *s) { int count = 0, in_word = 0; for (; *s; s++) { if (*s != ' ' && !in_word) { count++; in_word = 1; } else if (*s == ' ') { in_word = 0; } } return count; }
Q2. What is the output of the following code? Explain. `int a[3] = {1,2,3}; printf("%d", *(a+1) + *(a+2));`
Show Solution
Output: 5. `*(a+1)` = a[1] = 2, `*(a+2)` = a[2] = 3. 2+3 = 5.
Q3. Explain what a dangling pointer is and how to avoid it.
Show Solution
A dangling pointer points to memory that has been freed. Example: `int *p = malloc(4); free(p); *p = 10;` is undefined behavior. To avoid: set pointer to NULL after free, or use a memory ownership discipline (single owner).
Q4. What is the difference between `malloc` and `calloc`? Give a use case for each.
Show Solution
malloc(n) allocates n bytes uninitialized. calloc(m, n) allocates m*n bytes, zero-initialized. Use malloc when you will immediately overwrite all bytes; use calloc when you need zero-initialized memory (e.g., arrays of structs).