Optimization and Debugging
Optimization Strategies
Optimization Levels
graph TD
A[GCC Optimization Levels] --> B[-O0: No Optimization]
A --> C[-O1: Basic Optimization]
A --> D[-O2: Recommended Optimization]
A --> E[-O3: Aggressive Optimization]
// Inefficient Code
int calculate_sum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// Optimized Code
int optimized_sum(int arr[], int size) {
int sum1 = 0, sum2 = 0;
for (int i = 0; i < size; i += 2) {
sum1 += arr[i];
sum2 += arr[i+1];
}
return sum1 + sum2;
}
Optimization Comparison
Optimization Flag |
Compilation Time |
Code Performance |
Binary Size |
-O0 |
Fastest |
Lowest |
Smallest |
-O1 |
Fast |
Moderate |
Small |
-O2 |
Moderate |
Good |
Medium |
-O3 |
Slow |
Best |
Largest |
Debugging Techniques
GDB Debugging
## Compile with debug symbols
gcc -g program.c -o program_debug
## Start debugging
gdb ./program_debug
Common GDB Commands
Command |
Description |
break main |
Set breakpoint at main function |
run |
Start program execution |
next |
Execute next line |
print variable |
Print variable value |
backtrace |
Show call stack |
Memory Debugging
#include <stdlib.h>
void memory_leak_example() {
int *ptr = malloc(sizeof(int) * 10);
// Missing free(ptr)
}
Valgrind Memory Analysis
## Install Valgrind
sudo apt-get install valgrind
## Memory check
valgrind --leak-check=full ./program
## Compile with profiling
gcc -pg program.c -o program_profile
## Generate profile data
./program_profile
gprof program_profile gmon.out
Compiler Sanitizers
Address Sanitizer
## Compile with Address Sanitizer
gcc -fsanitize=address -g program.c -o program_sanitized
Undefined Behavior Sanitizer
## Compile with Undefined Behavior Sanitizer
gcc -fsanitize=undefined -g program.c -o program_ub
LabEx Optimization Tips
- Use appropriate optimization levels
- Enable compiler warnings
- Use debugging and profiling tools
- Test different optimization strategies
Advanced Optimization Techniques
Inline Functions
// Suggest compiler to inline
static inline int max(int a, int b) {
return (a > b) ? a : b;
}
Loop Unrolling
// Manual loop unrolling
for (int i = 0; i < 100; i += 4) {
process(arr[i]);
process(arr[i+1]);
process(arr[i+2]);
process(arr[i+3]);
}
By mastering these optimization and debugging techniques, developers can create more efficient and reliable C programs on platforms like LabEx.