Appendix A — Pointers in C
TipRecommended by ChatGPRT
- Preamble
- Introduce the importance of pointers in C
- Highlight that pointers are used for:
- Dynamic memory management
- Function callbacks / OOP in C
- Low-level memory access (e.g., MMIO in system programming)
- Pointer basics
- Pointer declaration, initialization, and dereferencing (
*p) NULLpointer and wild/invalid pointers- Pointer arithmetic and relationship with arrays (
ptr[i] == *(ptr + i)) sizeofand pointer types
- Pointer declaration, initialization, and dereferencing (
- Functions and Function Pointers
- Passing-by-Value vs. Passing-by-Reference
- How C passes arguments by value
- Using pointers to modify caller variables
- Double pointers (
int **p) for dynamic structures
- Function Pointer
- Declaration and initialization
- Invoking functions through pointers
- Use cases: callbacks, table-driven design, Linux Kernel hooks, OOP-like vtables
- Passing-by-Value vs. Passing-by-Reference
- Dynamic Memory Allocation
malloc,calloc,realloc,free- Pointer to allocated memory
- Pointer arrays vs pointer-to-pointer
- Pointer to Void (
void *)- Generic memory buffers
- Casting to proper type for access
- Pointer with
volatilekeyword- Purpose: prevent compiler optimization on memory-mapped hardware or shared memory
- Examples: MMIO, flags in embedded systems
- Common Pitfalls about Pointers
- Dangling Pointer
- Definition and causes (e.g., freed memory, local variable address)
- How to avoid
- Double-Free and Use-After-Free
- Examples and consequences
- Best practices for safe memory management
- Indexing Overflow / Buffer Overflow
- Pointer arithmetic mistakes
- Array bounds violations
- Tools for detection: Valgrind, ASAN
- Dangling Pointer
A.1 Preamble
In this chapter, we focus on the basic usages of pointers in C language, including normal pointer to data and function pointers.