Common C Bugs — Buffer Overflow, Dangling Pointers, UB
Learning Objectives
- Recognize classic C bugs from their symptoms
- Explain why buffer overflows and dangling pointers are dangerous
- Identify sources of undefined behavior
- Apply practical habits that prevent these mistakes
Why C Bugs Hit Hard
C trusts you to manage memory, types, and bounds. That freedom enables fast systems code, but mistakes do not always crash immediately. A wrong write may corrupt distant memory and surface much later as a strange failure. Learning the common bug families helps you prevent them and debug them faster when they appear.
Buffer Overflow
A buffer overflow writes past the end of an array or allocated block. It can overwrite other variables, return addresses, or heap metadata. Overflow bugs are a major source of both crashes and security vulnerabilities.
char name[5];
strcpy(name, "Alexander");
printf("%s\n", name);
The source string needs more bytes than name can hold, so the copy runs off the end. Prevention strategies include checking lengths before copy, using width-limited reads, and choosing buffer sizes with room for the terminator and realistic input.
| Defense | Idea |
|---|---|
| Bounded copy | Never exceed destination capacity |
| Width limits | Cap scanf string fields |
| fgets line reads | Respect the size argument |
| Assertions | Catch impossible states early |
Dangling Pointers
A dangling pointer still holds an address, but the object it referenced is gone. Common causes include returning a pointer to a local variable, using memory after free, and referring to stack storage after its function returned.
int *bad(void) {
int local = 10;
return &local;
}
When bad returns, local's storage disappears and the address is invalid. Reading or writing through that pointer is undefined. The safe pattern is to allocate with heap functions and transfer ownership clearly, or to return values instead of addresses to ephemeral storage.
After free, set your pointer to null and avoid retaining stale copies elsewhere. Only free pointers your code actually owns.
Uninitialized Reads and Off-by-One Errors
Automatic variables start with indeterminate values. Reading them before assignment yields garbage that varies by platform and optimization level. Always initialize or assign before use.
Off-by-one errors appear whenever loop bounds or index math are slightly wrong. Remember that valid indexes run from zero up to length minus one, and that a one-past-the-end pointer may be formed but not dereferenced.
int arr[3] = {1, 2, 3};
for (int i = 0; i <= 3; i++) {
printf("%d\n", arr[i]);
}
That final iteration reads invalid memory. Using a strict less-than comparison with the length prevents the classic mistake.
Undefined Behavior
Undefined behavior means the standard imposes no required result. The program might crash, print nonsense, or appear to work until a compiler update changes results. Common triggers include signed overflow, null dereference, strict aliasing violations, and evaluating an expression multiple times with side effects inside unsafe macros.
int x = 2147483647;
x = x + 1;
printf("%d\n", x);
For a typical 32-bit int, that increment overflows a signed value, which is undefined. Prefer wider types, checked arithmetic, or unsigned types when wraparound is acceptable by design.
🚨Undefined Behavior Is Not Predictable
Code that seems fine under one compiler flag set can break under another. Treat undefined behavior as a bug to eliminate, not as a quirk to depend on.
Prevention Habits
Compile with strong warnings and read every message. Use tools such as sanitizers or static analyzers when available. Keep functions small so bounds are visible. Initialize variables at declaration. Free each allocation once and null the pointer. Write tests for empty, full, and boundary conditions.
Debugging becomes easier when you can name the bug family quickly. Overflow suggests buffer sizing. Garbage values suggest uninitialized reads or type confusion. Random crashes after free suggest double free or dangling access.
Key Takeaways
💡
- Buffer overflows corrupt memory past array or allocation limits
- Dangling pointers reference storage that is no longer valid
- Uninitialized automatic variables hold indeterminate values
- Off-by-one loops read one slot beyond valid indexes
- Undefined behavior must be designed out, not tolerated
Practice Questions
- What are two common ways a dangling pointer is created?
- Why is an off-by-one loop bound dangerous for arrays?
- Name three habits that reduce the chance of undefined behavior.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions