Chapters & contents Lesson 5 of 15
3 min read
C programmingExpanded reading

Array bounds and object lifetimes

Follow valid memory accesses rather than guessing from addresses.

What you’ll learn

  • Identify valid array indexes
  • Explain why length must travel with a pointer
  • Distinguish an object from a pointer to it

An array has a fixed extent

A C array is a sequence of elements with one element type. If an array contains four integers, the valid element indexes are zero through three. An index expression does not automatically check this boundary for you. Begin each access by asking where the index came from and which bound proves that it is valid. A program appearing to work with a fifth element is not evidence of correctness; an invalid access can have undefined behavior.

Carry the count across a boundary

When an array expression is used in many ordinary expressions, it becomes a pointer to its first element. That pointer alone does not describe the number of accessible elements. A function that processes a buffer therefore often needs a separate element count and a clear contract connecting that count to the supplied object. Do not use sizeof on a pointer parameter and expect the original array length. Review the caller and the callee together when checking this contract.

Trace a small loop

Suppose samples contains three readings: 4, 7, and 2. A loop beginning at zero and continuing while the index is less than three visits exactly those readings. The sum becomes four, eleven, and thirteen. Changing the condition to less than or equal to three permits an extra iteration. Write the index and the element selected on paper before running an unfamiliar loop. Boundary traces expose mistakes that a single happy-path output can conceal.

c · Worked example
#include <stddef.h>
#include <stdio.h>

int main(void) {
    int samples[] = {4, 7, 2};
    int total = 0;
    for (size_t i = 0; i < 3; ++i) {
        total += samples[i];
    }
    printf("%d\n", total);  /* 13 */
    return 0;
}

A pointer does not extend lifetime

An automatic local object normally stops existing when its enclosing block ends. Returning a pointer to such an object does not keep it alive. Similarly, after dynamically allocated storage has been freed, keeping a copied pointer does not make dereferencing it valid. Ownership, lifetime, and accessible extent are related questions, but they are not interchangeable. Document which component owns a buffer and how long a borrowed pointer may be used.

Make failures visible during development

Test empty inputs, a single element, and the largest valid count permitted by your interface. Enable compiler warnings and use suitable runtime checking tools during development, while remembering that a clean run does not prove all inputs safe. Prefer the simplest contract that meets the task. If a function never needs to change the input elements, communicate that intention with a pointer to const-qualified elements and still validate the relevant count at the boundary.

Try it yourself

A three-element array is processed by a loop with i <= 3. List the indexes visited and correct the loop condition.

Show a possible solution

The indexes are 0, 1, 2, and 3. Index 3 is outside this array. Use i < 3, with a count that accurately describes the supplied array.

Check your understanding

Try 11 questions across c programming. Read each explanation and revisit anything that needs another pass.

Practise this subject

Go to the source

Use these primary references to check details and explore the topic further.

Saved in this browser. Signed-in progress syncs to your account.