Skip to content

Sizes and Arithmetic Boundaries

The Course
•
35 min study

A collection needs numbers that describe itself: how many records are active, how many fit, and how many bytes they occupy. Those numbers are where many C bugs start. Ask an empty list for "the last record" and the computation count - 1 does not produce -1. It produces the largest number the type can hold, and the next line reads far outside the array. This lesson shows how C's size arithmetic really behaves and the small checks that keep it honest.

Predict and run

Read the program before pressing Run. Write down its output and explain which statement produces each number.

Predict before running C
#include <stdio.h>
#include <stddef.h>

int main(void) {
    size_t count = 3;
    int values[3] = {10, 20, 30};
    if (count > 0) { printf("%zu %d\n", count, values[count - 1]); }
    return 0;
}
Check your prediction
Text
3 30

The count is 3, so the last valid index is 2 and the program prints the third element. The guard count > 0 matters more than it looks: it is the only thing standing between this code and the wrap-around you will see next.

size_t is unsigned, and unsigned wraps

size_t is the unsigned integer type that sizeof produces and that the standard library uses for sizes and counts. Declare it with <stddef.h> and print it with %zu. Unsigned types cannot hold negative values. Instead, their arithmetic is defined to wrap around modulo a power of two, so subtracting 1 from 0 gives the maximum value, SIZE_MAX (from <stdint.h>):

Subtract from an empty count C
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

int main(void) {
    size_t count = 0;
    size_t last = count - 1;
    printf("wrapped to SIZE_MAX: %s\n", last == SIZE_MAX ? "yes" : "no");
    printf("last < count: %s\n", last < count ? "yes" : "no");
    return 0;
}
Text
wrapped to SIZE_MAX: yes
last < count: no

Wrapping is well defined, so the compiler does not warn. It is still almost always a logic error for sizes. The second line shows the rule that saves you: test index < count before using an index, and never compute count - 1 until you know count > 0.

The same wrap breaks a familiar countdown loop. for (size_t i = n - 1; i >= 0; --i) never ends, because an unsigned i >= 0 is always true. GCC and Clang flag the comparison with -Wextra. Count down like this instead, so the test happens before the decrement:

Count down safely C
#include <stdio.h>
#include <stddef.h>

int main(void) {
    int values[3] = {10, 20, 30};
    for (size_t i = 3; i-- > 0;) {
        printf("%d\n", values[i]);
    }
    return 0;
}
Text
30
20
10

Mixing signed and unsigned

When a comparison mixes int and size_t, the int is converted to size_t first. A negative index becomes a huge positive number:

C
int index = -1;
size_t count = 3;
if (index < count) {   /* -1 becomes SIZE_MAX, so this is false */
    puts("in range");
}

In a local build with -Wall -Wextra -Werror, the comparison is a compile error (the browser editor builds without warning flags, so there it just runs and gives the wrong answer): -Wextra turns on -Wsign-compare, and -Werror makes the warning fatal. Keep counts and indexes as size_t from start to finish, and convert signed input once, after checking that it is not negative.

Signed overflow is undefined behavior

Signed integers do not wrap. If int arithmetic overflows, the behavior is undefined, and compilers optimize on the assumption that it never happens. For example, a compiler may simplify x + 1 > x to "always true" for an int x, because the only case where it is false is an overflow it is allowed to ignore.

This matters for totals. The standard only guarantees that int reaches 32767, but the analyzer can store 1024 records of up to 180 minutes, which is 184320 minutes. long is guaranteed to reach at least 2147483647, so report totals use long. Choose the type from the largest value your contract allows, not from today's test data.

Check a multiplication before you do it

A byte count is count * sizeof element. If the product does not fit, unsigned multiplication wraps to a small number, and a later allocation would be far too small. You cannot detect this afterward by looking at the product, so check with division first:

Check the product with division C
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

int bytes_fit(size_t count) {
    return count <= SIZE_MAX / sizeof(int);
}

int main(void) {
    printf("10 ints: %s\n", bytes_fit(10) ? "fits" : "too large");
    printf("SIZE_MAX ints: %s\n", bytes_fit(SIZE_MAX) ? "fits" : "too large");
    return 0;
}
Text
10 ints: fits
SIZE_MAX ints: too large

SIZE_MAX / sizeof(int) is the largest count whose product cannot exceed SIZE_MAX. Division never overflows, so the check itself is safe. Day 2 uses exactly this guard before every allocation.

Practice

Exercise

Your turn

Write int sum_last(const int values[], size_t count, size_t n, long *out). It adds the last n values. If n > count, it returns 0 and leaves *out unchanged. Otherwise it stores the sum and returns 1. Summing the last 0 values gives 0. With the starter's data, the program should print last 2: 70, last 4: 100, last 0: 0 and last 5: rejected, still 0, one per line.

The starter's show helper is marked static. On a function at file scope, static keeps the name private to this file; Day 6's lesson on headers explains why that matters. Here you can read it as "a helper only this file uses".

Your workspace C
#include <stdio.h>
#include <stddef.h>

/* Write sum_last here. */

static void show(const int values[], size_t count, size_t n, long *total) {
    if (sum_last(values, count, n, total)) {
        printf("last %zu: %ld\n", n, *total);
    } else {
        printf("last %zu: rejected, still %ld\n", n, *total);
    }
}

int main(void) {
    int values[4] = {10, 20, 30, 40};
    long total = -1;
    show(values, 4, 2, &total);
    show(values, 4, 4, &total);
    show(values, 4, 0, &total);
    show(values, 4, 5, &total);
    return 0;
}
Hint 1: the idea

The first index to add is count - n. That subtraction is only safe once you know n <= count; with n equal to 5 it would wrap to a huge index.

Hint 2: a first step

Write only the rejection and run: the last 5 line should already say rejected, and nothing has been added yet. Before you write the loop, work out on paper which index it must start at for last 2 with the starter's four values, and which for last 0.

Show one solution
Run the solution C
#include <stdio.h>
#include <stddef.h>

int sum_last(const int values[], size_t count, size_t n, long *out) {
    if (n > count) { return 0; }
    long total = 0;
    for (size_t i = count - n; i < count; ++i) {
        total += values[i];
    }
    *out = total;
    return 1;
}

static void show(const int values[], size_t count, size_t n, long *total) {
    if (sum_last(values, count, n, total)) {
        printf("last %zu: %ld\n", n, *total);
    } else {
        printf("last %zu: rejected, still %ld\n", n, *total);
    }
}

int main(void) {
    int values[4] = {10, 20, 30, 40};
    long total = -1;
    show(values, 4, 2, &total);
    show(values, 4, 4, &total);
    show(values, 4, 0, &total);
    show(values, 4, 5, &total);
    return 0;
}
Text
last 2: 70
last 4: 100
last 0: 0
last 5: rejected, still 0

The guard turns the dangerous subtraction into a safe one: after n <= count, count - n is between 0 and count. When n is 0, the loop starts at count and runs zero times, so the empty case needs no special code. The sum goes into a local long and is committed once at the end, the validate-then-commit pattern from the previous lesson. Next, you will give failures names instead of returning a bare 0.

Was this article helpful?

Your response is saved on this device.