Undefined Behaviour in C and C++

In C programming, undefined behavior refers to situations where the language standard does not specify what should happen. When undefined behavior occurs, the program may produce unpredictable results, crash, or appear to work correctly but fail later under different conditions.

Syntax

/* Undefined behavior occurs when code violates C language rules */
/* Examples: dereferencing NULL pointers, buffer overflows, etc. */

Common Examples of Undefined Behavior in C

1. Division by Zero

Division by zero in C leads to undefined behavior. The program may crash, produce garbage values, or behave unpredictably ?

Example

#include <stdio.h>

int main() {
    int x = 10, y = 0;
    int result = x / y;  /* This causes undefined behavior */
    printf("Result: %d\n", result);
    return 0;
}
Runtime error (program may crash or produce unpredictable output)

2. Using Uninitialized Variables

Reading from uninitialized automatic variables leads to undefined behavior because they contain garbage values ?

Example

#include <stdio.h>

int main() {
    int x;  /* Uninitialized variable */
    printf("Value of x: %d\n", x);  /* Undefined behavior */
    return 0;
}
Value of x: [unpredictable garbage value]

3. Dereferencing NULL Pointers

Attempting to access memory through a NULL pointer results in undefined behavior, typically causing a segmentation fault ?

Example

#include <stdio.h>

int main() {
    int *ptr = NULL;
    printf("Value: %d\n", *ptr);  /* Dereferencing NULL pointer */
    return 0;
}
Segmentation fault (core dumped)

4. Signed Integer Overflow

When a signed integer exceeds its maximum value, overflow behavior is undefined in C ?

Example

#include <stdio.h>
#include <limits.h>

int main() {
    int x = INT_MAX;
    printf("INT_MAX: %d\n", x);
    printf("INT_MAX + 1: %d\n", x + 1);  /* Undefined behavior */
    return 0;
}
INT_MAX: 2147483647
INT_MAX + 1: -2147483648

5. Modifying String Literals

String literals are stored in read-only memory. Attempting to modify them results in undefined behavior ?

Example

#include <stdio.h>

int main() {
    char *str = "Hello";
    str[0] = 'h';  /* Undefined behavior - modifying string literal */
    printf("%s\n", str);
    return 0;
}
Segmentation fault (or unpredictable behavior)

How to Avoid Undefined Behavior

  • Always initialize variables before use
  • Check for NULL pointers before dereferencing
  • Validate input ranges to prevent overflow
  • Use array bounds checking
  • Compile with warnings enabled (-Wall -Wextra)

Conclusion

Undefined behavior in C can lead to unpredictable program execution, security vulnerabilities, and hard-to-debug errors. Understanding and avoiding these situations is crucial for writing reliable C programs.

Updated on: 2026-03-15T10:42:52+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements