What is undefined behavior in C?

Undefined behavior (UB) means the C standard gives no rule about what the program will do. It may work, crash, or give a wrong result, and it can change with the compiler or the options.

Common examples:

  • Reading an uninitialized variable.
  • Accessing an array outside its limits.
  • Dereferencing a NULL or dangling pointer.
  • Signed integer overflow, like INT_MAX + 1.
  • Modifying a variable two times in one expression, like i = i++ + ++i.
  • Dividing by zero.

The danger is that the program may look fine on your computer. Compile with -Wall -Wextra and use -fsanitize=undefined to catch many of them.


Learn more about the similar topics:
Tutorials
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?