BETA Try the new lesson view
Theory

Extra: how does the CPU see it?

Extra. Not graded. How does the processor find a[i]?

Open the tool window's Assembly tab. On the left is your practice/06/search.c.

An index is an address calculation

An array in memory is its elements one after another. The address of a[i] = the start of the array + i · the size of an element. In linear_search, the line if (a[i] == x) shows it directly:

  • lea rdx, 0[0+rax*4]: i · 4 (an int takes 4 bytes);
  • add rax, rdx: added to the start of the array a;
  • mov eax, DWORD PTR [rax]: the 4 bytes at that address are read.

There is no check that i stays inside the array: the processor simply reads whatever is at that address. That is why C doesn't report an error out of bounds but reads "something", and only the sanitizers catch it.

What to notice (-O0)

  • The parameter a is stored as a QWORD (8 bytes): the function gets not the array but its address.
  • The global checks is reached by name (checks[rip]), local variables through rbp: a global lives in one place for the program's whole run.
  • (right - left) / 2 becomes shr, add, sar: dividing by 2 is a shift by one bit (with a correction for negative numbers).

Switch to -O1: the whole of a[i] == x fits in one instruction, cmp DWORD PTR [rcx+rax*4], ...: the processor can compute the address "start + index · 4" by itself.