ProgrammingC Developer

What is 'undefined behavior' in C language? Provide examples of its occurrence and ways to minimize such problems.

Pass interviews with Hintsage AI assistant

Answer.

Undefined Behavior (UB) is a behavior of a program whose result is not defined by the C language standard. The compiler or system may perform any action — from silent errors to complete crashes or data corruption.

Typical causes of UB:

  • Accessing out of bounds of an array
  • Dereferencing an uninitialized/invalid pointer
  • Division by 0
  • Modifying constants

How to minimize UB:

  • Always initialize variables
  • Check array indices
  • Use static and dynamic code analyzers (e.g., valgrind, AddressSanitizer)

Code example:

int arr[5]; arr[10] = 0; // UB — out of bounds access int* p = NULL; *p = 42; // UB — dereferencing NULL pointer

Tricky question.

Question: What happens if you perform integer division by zero?

Answer: According to the C standard (ISO C99 6.5.5), division by 0 is undefined behavior. A crash, junk data, or even a "logically correct" output is possible, but the standard does not guarantee any result.

Code example:

int a = 10, b = 0; printf("%d", a / b); // Undefined behavior

Story

In one of the embedded systems projects, a programmer wrote a loop over an array and accidentally went one element out of bounds. The application worked fine, but after a month, data corruption started occurring in other memory (temporary errors, hard to reproduce). The problem was found only after careful review and checking with a static analyzer.


Story

A developer relied on the fact that dereferencing a NULL pointer always causes a crash and therefore did not add NULL checks. However, on a rare platform, this led to incorrect (but not fatal) memory modification, which broke other structures and led to elusive bugs.


Story

When generating pseudo-random numbers, division was used, and for certain values of input arguments, division by 0 occurred. On most platforms, the program just "crashed," but on one, the result was an incorrect number, making it impossible to reproduce bugs between different environments.