C Undefined Behavior
Understanding undefined behavior in C programming.
1. Common Undefined Behaviors
Integer Overflow
c
int x = INT_MAX;
x = x + 1; // Undefined behaviorArray Out of Bounds
c
int arr[5];
arr[5] = 10; // Undefined behaviorUninitialized Variables
c
int x;
printf("%d\n", x); // Undefined behaviorDouble Free
c
int *ptr = malloc(sizeof(int));
free(ptr);
free(ptr); // Undefined behaviorUse After Free
c
int *ptr = malloc(sizeof(int));
free(ptr);
*ptr = 10; // Undefined behavior2. Pointer Issues
c
int *ptr = NULL;
*ptr = 10; // Undefined behavior
int *ptr2;
*ptr2 = 10; // Undefined behavior (uninitialized pointer)3. Function Return
c
int func() {
// No return statement - undefined behavior if return value is used
}
int main() {
int x = func(); // Undefined behavior
return 0;
}4. Prevention
- Initialize all variables
- Check array bounds
- Validate pointers
- Use compiler warnings
- Use static analysis tools