Defensive Programming
Safe Arithmetic Techniques
Checking Before Calculation
int safe_multiply(int a, int b) {
if (a > 0 && b > INT_MAX / a) return -1;
if (a < 0 && b < INT_MAX / a) return -1;
return a * b;
}
Overflow Detection Strategies
graph TD
A[Arithmetic Operation] --> B{Check Limits}
B -->|Safe| C[Perform Calculation]
B -->|Risky| D[Handle Potential Overflow]
Recommended Practices
Strategy |
Description |
Example |
Explicit Range Checking |
Validate input before calculation |
Verify input against type limits |
Safe Conversion |
Use careful type casting |
Check value ranges during conversion |
Error Handling |
Implement robust error management |
Return error codes or use exceptions |
Safe Multiplication Implementation
#include <limits.h>
#include <stdbool.h>
bool safe_multiply(int a, int b, int* result) {
if (a > 0 && b > 0 && a > INT_MAX / b) return false;
if (a > 0 && b < 0 && b < INT_MIN / a) return false;
if (a < 0 && b > 0 && a < INT_MIN / b) return false;
if (a < 0 && b < 0 && a < INT_MAX / b) return false;
*result = a * b;
return true;
}
Compiler Warnings and Static Analysis
Enabling Overflow Checks
gcc -Wall -Wextra -Woverflow -O2 your_program.c
Advanced Overflow Protection
Using Builtin Functions
#include <stdlib.h>
int main() {
int a = 1000000;
int b = 1000000;
int result;
if (__builtin_smul_overflow(a, b, &result)) {
// Handle overflow
fprintf(stderr, "Multiplication overflow detected\n");
}
return 0;
}
Defensive Programming Principles
At LabEx, we recommend:
- Always validate input ranges
- Use appropriate data types
- Implement explicit overflow checks
- Utilize compiler warnings
- Conduct comprehensive testing
Error Handling Pattern
enum CalculationResult {
CALC_SUCCESS,
CALC_OVERFLOW,
CALC_INVALID_INPUT
};
enum CalculationResult safe_divide(int a, int b, int* result) {
if (b == 0) return CALC_INVALID_INPUT;
if (a == INT_MIN && b == -1) return CALC_OVERFLOW;
*result = a / b;
return CALC_SUCCESS;
}