Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is undefined behavior in C?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring