C Notes
Fix common C programming errors including segmentation fault, memory leaks, buffer overflow, undefined behavior, linker errors, and compilation warnings with solutions.
Every C programmer encounters errors that seem cryptic at first. Unlike languages with managed runtimes, C's errors often manifest as crashes, corrupted data, or silently wrong results. This guide covers the most common errors, explains why they happen, and shows you how to fix them.
Compilation Errors
Error 1: Implicit Function Declaration
// Error: implicit declaration of function 'strlen'
#include <stdio.h>
int main() {
char str[] = "Hello";
int len = strlen(str); // Missing #include <string.h>
printf("Length: %d\n", len);
return 0;
}Fix: Include the correct header file.
#include <stdio.h>
#include <string.h> // Add this!Error 2: Incompatible Pointer Types
// Warning: incompatible pointer types
int *ptr;
float x = 3.14;
ptr = &x; // int* = float* → wrong!Fix: Use the correct pointer type or cast explicitly.
float *ptr = &x; // Correct type
// Or if you really need it: int *ptr = (int*)&x; (but usually wrong)Error 3: Missing Semicolon
int main() {
int x = 10 // Missing semicolon
printf("%d\n", x); // Error points HERE, not the actual problem
return 0;
}Fix: The error message often points to the line AFTER the actual issue. Look at the previous line for the missing semicolon.
Error 4: Undeclared Variable
Fix: Declare the variable: for (int i = 0; i < 10; i++)
Linker Errors
Error 5: Undefined Reference
undefined reference to 'sqrt'
Fix: Link the math library:
// gcc program.c -lm
// The -lm flag links libm (math library)Error 6: Multiple Definition
multiple definition of 'globalVar'
This happens when a global variable is defined in a header that's included by multiple .c files.
Fix: Use extern in the header, define in one .c file:
// header.h
extern int globalVar; // Declaration only
// main.c
int globalVar = 42; // Definition in ONE fileRuntime Errors
Error 7: Segmentation Fault (SIGSEGV)
The most feared C error. It means you accessed memory you shouldn't have.
Common Causes and Fixes:
Error 8: Memory Leak
Memory is allocated but never freed. Program uses more and more memory over time.
// LEAK: Allocation without free
void processData() {
char *buffer = malloc(1024);
// ... use buffer ...
return; // Forgot to free!
}
// FIX: Always pair malloc with free
void processData() {
char *buffer = malloc(1024);
if (!buffer) return;
// ... use buffer ...
free(buffer); // Free before return!
}
// LEAK: Overwriting pointer before free
int *p = malloc(sizeof(int));
p = malloc(sizeof(int)); // First allocation lost!
// FIX: Free before reassigning
free(p);
p = malloc(sizeof(int));Detection: Use valgrind --leak-check=full ./program
Error 9: Buffer Overflow
Error 10: Double Free
int *p = malloc(sizeof(int));
free(p);
free(p); // UNDEFINED BEHAVIOR! Heap corruption
// FIX: Set to NULL after free
free(p);
p = NULL;
free(p); // free(NULL) is safe (no-op)Error 11: Using Uninitialized Variables
Error 12: Integer Overflow
#include <limits.h>
int a = INT_MAX; // 2147483647
int b = a + 1; // UNDEFINED BEHAVIOR for signed!
printf("%d\n", b); // Might print -2147483648
// FIX: Check before operation
if (a > INT_MAX - 1) {
printf("Overflow would occur!\n");
} else {
b = a + 1;
}Error 13: Format String Mismatch
int x = 42;
printf("%f\n", x); // WRONG: int printed as float
printf("%d\n", 3.14); // WRONG: float printed as int
long long big = 1234567890123LL;
printf("%d\n", big); // WRONG: only prints lower 32 bits
// FIX: Match format specifiers to types
printf("%d\n", x); // int
printf("%f\n", 3.14); // double
printf("%lld\n", big); // long longError 14: Returning Address of Local Variable
int* getNumber() {
int x = 42;
return &x; // x is destroyed after return! Dangling pointer!
}
// FIX Option 1: Use static
int* getNumber() {
static int x = 42;
return &x; // static lives for program lifetime
}
// FIX Option 2: Use malloc
int* getNumber() {
int *x = malloc(sizeof(int));
*x = 42;
return x; // Caller must free
}
// FIX Option 3: Pass buffer from caller
void getNumber(int *result) {
*result = 42;
}Error 15: String Modification of Literal
Error Summary Table
| Error | Symptom | Common Cause | Fix |
|---|---|---|---|
| Segfault | Program crashes | NULL deref, out of bounds | Check pointers, validate indices |
| Memory leak | Growing memory usage | Missing free() | Pair every malloc with free |
| Buffer overflow | Corruption, crash | strcpy, gets, no bounds | Use bounded functions |
| Double free | Corruption, crash | Free called twice | NULL after free |
| Uninit variable | Random behavior | Missing initialization | Initialize all variables |
| Dangling pointer | Random behavior | Return local address | Use malloc or static |
| Integer overflow | Wrong values | Arithmetic beyond limits | Check bounds |
| Format mismatch | Wrong output | Wrong printf specifier | Match types exactly |
Prevention Checklist
- Compile with warnings:
gcc -Wall -Wextra -Werror - Use sanitizers:
-fsanitize=address,undefined - Run Valgrind:
valgrind --leak-check=full ./program - Initialize everything: Variables, arrays, pointers
- Check all returns: malloc, fopen, scanf
- Use bounded functions: snprintf, fgets, strncpy
- Free in reverse order: Last allocated = first freed
- NULL after free: Prevents use-after-free
Interview Questions
Q: How do you debug a segfault with no obvious cause? Compile with -g -fsanitize=address, run the program. ASan gives exact line number and type of memory error. Alternatively, use GDB: run, get backtrace at crash point.
Q: How do you find where a memory leak occurs? Use valgrind --leak-check=full --show-leak-kinds=all. It shows the exact allocation call stack for every leaked block.
Q: What's the most dangerous C function and why? gets() – it cannot limit input size, guaranteeing buffer overflow. It was removed from the C11 standard. Use fgets() instead.
Summary
C programming errors fall into three categories: compilation errors (caught by compiler), linker errors (symbol resolution failures), and runtime errors (crashes and undefined behavior). The most dangerous are runtime errors because they can silently corrupt data or create security vulnerabilities. Master the tools (GCC warnings, ASan, Valgrind), follow defensive coding practices, and always validate your assumptions about memory and data.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Common C Programming Errors and Solutions – Debugging Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, resources, common, errors, and, solutions
Related C Programming Topics