Brainlag
  1. Library
  2. Debugging
  3. C

memory access out of boundsWhat is "memory access out of bounds"?

The program read or wrote memory it does not own, far past an array or through a bad pointer. On a laptop the same bug is usually a segmentation fault.

C5 min

What the runtime is telling you

Output
RuntimeError: memory access out of bounds

This is a runtime error: the program compiled, started, then tried to touch an address outside the memory it owns. The machine stopped it on the spot. On a laptop the same bug usually says Segmentation fault.

Typical causes:

  • An index far too big, often from a loop whose limit is wrong, or an index that came from input and was never checked.
  • A pointer that points nowhere useful: never set, set to a nonsense number, or pointing at memory that was freed.

The tricky part: being just a little past the end of an array usually does not stop anything. It reads or overwrites a neighbour and gives wrong answers instead. Only far-off addresses trap.

How to find it

There is no line number, so make one. Put a printf before the suspicious loop or pointer use and print the index or the pointer (%p). Run again: the last line printed before the crash shows where it happened. Then ask the questions: how big is the array, and what is the biggest index this loop can reach? Where was this pointer last given a value?

Run it: an index nobody checked

Press Run and read the error from the bottom up.

main.c to run
#include <stdio.h>

int main(void) {
    int inventory[5] = {3, 0, 1, 7, 2};
    int slot = 50000000;
    printf("checking slot %d\n", slot);
    inventory[slot] = 1;
    printf("saved\n");
    return 0;
}

The slot number from the player

A player types an inventory slot to use one item from it. Slot 2 works. A player who types 40000000 crashes the game. Make the program check the slot first and print no slot 40000000 instead. Check runs both inputs.

Checks

  1. Slot 2
  2. Slot 40000000
exercise_1.c to run
#include <stdio.h>

int main(void) {
    int inventory[5] = {3, 0, 1, 7, 2};
    int slot = 0;
    scanf("%d", &slot);

    inventory[slot] = inventory[slot] - 1;
    printf("used one from slot %d, %d left\n", slot, inventory[slot]);
    return 0;
}

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.