What is undefined behavior in C?

The language C does not provide direct support for exception handling.

This means that there is no mechanism to trap errors. In some cases, the code may continue to execute with errors.

Details

In such situations, the compiler’s behavior becomes unpredictable, or undefined.

Compiler behavior is unpredictable once it executes an error statement

Anything can happen, which may include the following:

  1. Program Crash: The entire program may crash citing any error as the reason

  2. Unpredictable Results: The program may generate incorrect or garbage output

  3. Data Corruption: The compiler may corrupt data which could lead to several other problems

Code

Let’s look at an example for undefined behavior:

#include <stdio.h>
#include <stdlib.h>
int main(){
// We will try to access arr[5] which is out of bounds
int arr[5] = {0, 1, 2, 3, 4};
int i = 0;
for(; i <= 5; i++)
printf("%d\n", arr[i]);
return 0;
}

In the above case, we try to access the 5th element in the array, which is out of bounds.

The compiler continues execution, regardless of the error. As a result, the 5th output is undefined.

There is no way to predict what we will get as our 5th output.

The tolerance for undefined behavior in C allows for faster compilation of code due to fewer checks.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved