Skip to content

C Undefined Behavior

Understanding undefined behavior in C programming.

1. Common Undefined Behaviors

Integer Overflow

c
int x = INT_MAX;
x = x + 1;  // Undefined behavior

Array Out of Bounds

c
int arr[5];
arr[5] = 10;  // Undefined behavior

Uninitialized Variables

c
int x;
printf("%d\n", x);  // Undefined behavior

Double Free

c
int *ptr = malloc(sizeof(int));
free(ptr);
free(ptr);  // Undefined behavior

Use After Free

c
int *ptr = malloc(sizeof(int));
free(ptr);
*ptr = 10;  // Undefined behavior

2. 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

Content is for learning and research only.