Reading history

Undefined Behaviour in C: Common Cases and Safe Code

7 min read Updated 4 views

Understand undefined behaviour in C: signed overflow, out-of-bounds access, use after free, string literals and evaluation order, plus safe code and sanitizers.

The C standard lists situations it does not define: reading outside an array, overflowing a signed integer, using memory after freeing it, and more. In these cases of undefined behaviour (UB), anything is allowed. The program might seem to work, print garbage, crash, or behave differently when compiled with optimisation turned on. UB is behind many security holes in real software, so every C programmer needs to recognise the common cases and know the safe way to write each one. All the examples here use the safe versions.

In this lesson you will learn

  • What UB means and why it is dangerous
  • Checking for signed integer overflow before it happens
  • Bounds checking, initialising variables and safe shifts
  • Avoiding use-after-free, buffer overflows and string literal changes
  • Tools that catch UB: warnings and sanitizers

You should know pointers, arrays and dynamic memory allocation.

Integers, Arrays and Shifts

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

/* Signed overflow is undefined, so check BEFORE adding */
static int safe_add(int a, int b, int *out) {
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
        return 0;                       /* would overflow */
    *out = a + b;
    return 1;
}

/* Reading outside an array is undefined, so check the index first */
static int get(const int *a, int n, int i, int *out) {
    if (i < 0 || i >= n) return 0;
    *out = a[i];
    return 1;
}

int main(void) {
    int r;
    printf("100 + 200: %s\n", safe_add(100, 200, &r) ? "ok" : "overflow");
    printf("INT_MAX + 1: %s\n", safe_add(INT_MAX, 1, &r) ? "ok" : "overflow");
    printf("INT_MIN + (-1): %s\n", safe_add(INT_MIN, -1, &r) ? "ok" : "overflow");

    /* Unsigned arithmetic is defined: it wraps around modulo 2^N */
    unsigned int u = UINT_MAX;
    u = u + 1;
    printf("UINT_MAX + 1 = %u (wraps, well defined)\n", u);

    int marks[5] = {70, 82, 91, 66, 88};
    int v;
    for (int i = 3; i <= 5; i++) {
        if (get(marks, 5, i, &v)) printf("marks[%d] = %d\n", i, v);
        else printf("marks[%d] is out of bounds: refused\n", i);
    }

    /* Always initialise variables before reading them */
    int total = 0;
    for (int i = 0; i < 5; i++) total += marks[i];
    printf("total = %d\n", total);

    /* Shifting by the type's width or more is undefined; keep shifts in range */
    int bits = 31;
    printf("1u << %d = %u\n", bits, 1u << bits);
    return 0;
}

Output

100 + 200: ok
INT_MAX + 1: overflow
INT_MIN + (-1): overflow
UINT_MAX + 1 = 0 (wraps, well defined)
marks[3] = 66
marks[4] = 88
marks[5] is out of bounds: refused
total = 397
1u << 31 = 2147483648
  • If the sum of two int values does not fit, that is UB. It often wraps to a negative number, but the compiler may assume it never happens and drop your later checks. safe_add tests a > INT_MAX - b before adding, which can never overflow itself.
  • Unsigned maths is well defined: it wraps around, so UINT_MAX + 1 is 0.
  • Reading marks[5] in a 5-element array is UB, even if it “works” in a test. get checks the index first.
  • Reading a local variable before you set it is UB; start totals at 0.
  • A shift by a negative count, or by the type’s width (32 for a 32-bit int) or more, is UB. 1u << 31 is fine on an unsigned; 1 << 31 on an int overflows.

Memory, Strings and Evaluation Order

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    /* 1. Use after free: set pointers to NULL after freeing and check them */
    int *scores = malloc(3 * sizeof *scores);
    if (scores == NULL) return 1;
    scores[0] = 90;
    free(scores);
    scores = NULL;
    if (scores == NULL) printf("scores was freed; not using it again\n");

    /* 2. Modifying a string literal is undefined: copy it into an array first */
    const char *literal = "dhaka";
    char city[16];
    strcpy(city, literal);
    city[0] = 'D';
    printf("city = %s\n", city);

    /* 3. Buffer overflow: bound every copy by the destination size */
    char small[8];
    const char *long_name = "Chattogram";
    size_t len = strlen(long_name);
    if (len >= sizeof small) len = sizeof small - 1;   /* leave room for '\0' */
    memcpy(small, long_name, len);
    small[len] = '\0';
    printf("small = %s (safely truncated)\n", small);

    /* 4. Unsequenced changes: do one change per statement */
    int i = 5;
    int a = i;          /* instead of something like  a = i++ + i++; */
    i++;
    int b = i;
    i++;
    printf("a = %d, b = %d, i = %d\n", a, b, i);

    /* 5. Dividing by zero is undefined for integers: check the divisor */
    int students = 0, total = 450;
    if (students != 0) printf("average = %d\n", total / students);
    else printf("no students: average not defined\n");
    return 0;
}

Output

scores was freed; not using it again
city = Dhaka
small = Chattog (safely truncated)
a = 5, b = 6, i = 7
no students: average not defined
  • Use after free: memory returned by free must not be read or written. Setting the pointer to NULL straight away turns a hidden bug into a check you can test.
  • String literals such as "dhaka" may sit in read-only memory, so changing one is UB. Copy it into a char array and change the copy.
  • Buffer overflow: copying “Chattogram” (10 characters) into an 8-byte array with strcpy would write past its end. The example limits the copy to 7 characters and adds '\0' itself.
  • Unsequenced changes: an expression such as i++ + i++ changes i twice with no defined order between the changes, so it is UB. Make one change per statement.
  • Integer division by zero is UB (often a crash). Check the divisor first.

Common Undefined Behaviour and the Safe Way

UndefinedSafe alternative
Signed integer overflowCheck against INT_MAX/INT_MIN first, or use a wider type
Array index out of boundsCheck 0 <= i && i < n
Reading an uninitialised variableInitialise every variable when you declare it
Dereferencing NULL or a freed pointerCheck for NULL; set pointers to NULL after free
Modifying a string literalUse a char array copy
Writing past a buffersnprintf, fgets and bounded copies
i = i++, a[i] = i++One side effect per statement
Integer division or % by zeroCheck the divisor
Shift by < 0 or ≥ widthKeep shift counts in range; shift unsigned values

Tools That Catch UB

Compile with warnings turned on and treated seriously: gcc -Wall -Wextra -Werror. Every example on this site is built that way, and GCC caught several problems while these lessons were being written. While testing, also try the sanitizers: gcc -g -fsanitize=address,undefined prog.c. AddressSanitizer reports out-of-bounds access and use-after-free, and UndefinedBehaviorSanitizer reports overflows, bad shifts and similar problems, each with the exact line. Valgrind is another option on Linux.

Common Mistakes

  1. “It works on my computer, so it is fine.” UB can change with a different compiler, optimisation level or input.
  2. Checking for overflow after it happens, such as if (a + b < a) with signed ints. The compiler may delete that check.
  3. Ignoring compiler warnings, which often point straight at UB.
  4. Assuming char is signed or that int is 32 bits in portable code.

Practice Exercises

Exercise 1. Write safe_mul(int a, int b, int *out) that refuses to multiply when the result would overflow.

Show answer
int safe_mul(int a, int b, int *out) {
    long long r = (long long)a * b;       /* fits: long long has at least 64 bits */
    if (r > INT_MAX || r < INT_MIN) return 0;
    *out = (int)r;
    return 1;
}

Doing the arithmetic in a type wide enough for any result is often the simplest overflow check.

Exercise 2. What is wrong with this code? char *p = malloc(5); strcpy(p, "Hello");

Show answer

“Hello” needs 6 bytes including '\0', so strcpy writes one byte past the allocation, a heap buffer overflow. Also, malloc may return NULL, which must be checked. Allocate strlen(s) + 1 bytes.

Frequently Asked Questions

What is the difference between undefined, unspecified and implementation-defined behaviour?

Implementation-defined behaviour must be written down by each compiler, such as the size of int. Unspecified behaviour allows a few choices, such as the order in which a call’s arguments are worked out. Undefined behaviour has no rules at all.

Why does C have undefined behaviour at all?

It lets compilers generate fast code for many different processors without adding checks to every operation. The price is that the programmer must avoid these situations.

Summary

  • UB means the C standard puts no limits on what happens.
  • Check for overflow, bounds and zero divisors before the operation.
  • Initialise variables, bound every copy and never use freed memory.
  • Compile with -Wall -Wextra and test with -fsanitize=address,undefined.

Next: Dynamic Arrays in C With realloc.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *