The idea: an array is bytes side by side

Memory is a long row of bytes, and each byte has an address. An array T a[n] is n elements of type T placed one right after another, with no gaps and no length stored next to them. So the compiler can find any element with one sum:

&a[i] = address of a[0] + i · sizeof(T)

Three byte rows starting at 0x1000. In a char array, a[3] starts 3 bytes in, at 0x1003. In an int array, a[3] starts 12 bytes in, at 0x100C. In a double array, a[3] starts 24 bytes in, at 0x1018.
The same a[3] is 3, 12 or 24 bytes from the start. The element type decides.

The canvas shows each small program on byte cells, 8 to a row, with toy addresses that start at 0x1000. A coloured band above the cells names the variable or element that owns them. Pick a statement and press Run, or run a demo. A grey box carries an address or a byte, one hop per step; orange cells are being read or written; red cells are touched by mistake.

Sizes on a typical x86-64 machine

The sum needs sizeof(T). On 64-bit Linux, macOS and Windows on x86-64 (and on arm64) the common sizes are these. The C standard only gives minimums; long is 4 bytes on 64-bit Windows.

Typesizeof&a[3] − &a[0]
char13 bytes
short26 bytes
int, float412 bytes
long, double, any pointer824 bytes

In Demo 1, a[3] is 'l' at 0x1003 in a char array, 40 at 0x100C in an int array, and 3.5 at 0x1018 in a double array. Finding a[3] or a[4000] costs the same: one multiply and one add. The bytes of an int or a double are stored lowest byte first (little-endian), so 40 is 28 00 00 00.

sizeof(a) on the array itself is the whole block: 5 · 4 = 20 for int a[5]. That is why sizeof(a) / sizeof(a[0]) gives the element count, but only where a is really the array (see below).

A 2D array is rows one after another

Memory has no rows and columns. int m[3][4] is an array of 3 rows, and each row is an array of 4 ints. C and C++ store row 0 first, then row 1, then row 2. This is row-major order. One row is 4 · 4 = 16 bytes, and the whole array is 48.

Top: a 3 by 4 grid holding 1 to 12, rows coloured blue, green and purple. Bottom: the same 12 ints in one row of memory, blue row first, then green, then purple. m[1][2], which holds 7, is element number 6, at 0x1018.
To reach m[r][c], skip r whole rows, then c more ints.

&m[r][c] = address of m + (r · 4 + c) · sizeof(int). In Demo 2, m[1][2] is element 1 · 4 + 2 = 6, at 0x1000 + 24 = 0x1018, and it holds 7. The last element m[2][3] is at 0x102C. The 4 in the formula is the column count, which is why a function parameter must spell it: void g(int m[][4]).

Order matters for speed. A loop that walks along a row reads bytes that sit next to each other, which the CPU cache likes. A loop that walks down a column jumps 16 bytes each time.

Passing an array to a function

A function cannot receive a whole C array. When you write f(a), the name a turns into the address of a[0], and only that 8-byte address is passed. A parameter written int a[] or even int a[5] is really int *a. This is the array decaying to a pointer.

Wherea issizeof(a)sizeof(a) / sizeof(a[0])
mainthe array, 5 ints20✓ 5
inside fa pointer to a[0]8✗ 2

a[i] still works inside f: it reads through the address. But the length is gone, so Demo 3 gets 2 instead of 5. Pass the length as a second parameter, f(a, 5), or use std::array or std::vector, which know their size. Compilers warn about sizeof on an array parameter (-Wsizeof-array-argument). Because only the address is passed, f also writes into the caller's array, not a copy.

C-strings end with '\0'

A C-string is a char array whose text ends with the byte 0, written '\0' (the terminator). Nothing stores the length. strlen starts at the first byte and counts until it meets a 0. char s[8] = "Ann"; fills 41 6E 6E 00 and then four more zeros.

Eight byte cells of char s[8]: A, n, n, then the terminator 00 and four more 00 bytes. strlen counts the first three cells and stops at the terminator, giving 3. sizeof covers all eight cells, giving 8.
strlen counts the chars before the first 0; sizeof counts the whole array.

So strlen(s) is 3 and sizeof(s) is 8 (Demo 4). A string literal like "Ann" takes 4 bytes, one more than its letters. Every buffer must have room for that extra byte.

When the bytes run out

strlen, strcpy, strcat and cout << on a char* trust the terminator and never look at the array's size. Two beginner bugs follow:

  • No terminator. char w[4] = {'a', 'b', 'c', 'd'}; has no '\0'. strlen(w) walks off the end into the next variable and stops only at some byte that happens to be 0. On the canvas that gives 5 (Demo 5).
  • Buffer too small. char buf[4]; holds at most 3 letters and the '\0'. strcpy(buf, "Hey") just fits. strcpy(buf, "Hello") writes 6 bytes; the last two, 'o' and '\0', land in count, which then reads 6F 00 00 00 = 111 instead of 7 (Demo 6). This is a buffer overflow.

Both are undefined behaviour. The program may seem fine, change a neighbour as here, or crash later far from the bug. Which neighbour gets hit depends on how the compiler placed the variables; the page puts count right after buf. Some builds catch it: on macOS the default strcpy checks the size it can see and stops the program.

CallWritesbufcount
strcpy(buf, "Hey")4 bytes"Hey"✓ 7
strcpy(buf, "Hello")6 bytes'H' 'e' 'l' 'l', no '\0'✗ 111
snprintf(buf, sizeof buf, "%s", "Hello")4 bytes"Hel"✓ 7

The fix is to pass the size. snprintf(buf, sizeof buf, "%s", src) writes at most sizeof buf − 1 chars and always ends with '\0'. It returns the length it wanted (5 in Demo 7), so r >= sizeof buf tells you the text was cut. Watch out: strncpy does not add a '\0' when the source is too long. In C++, std::string grows as needed and removes the whole problem. Attackers use the same mistake to overwrite more than a neighbour; Stack Buffer Overflow shows that side and the defences.

See also C++ Pointers for &, *p, p + 1 and why a[i] is *(a + i), Struct Padding and Alignment for how fields of different sizes are placed, Stack vs Heap in C for where local arrays and malloc blocks live, and Endianness for the byte order inside one int.

See also C++ Copying and the Rule of Three for a class that owns a heap array, and what goes wrong when it is copied.

What the page leaves out

Real addresses are large, change on every run, and a function's parameter lives in its own stack frame, not next to the caller's array. The compiler chooses the order and alignment of local variables, and with a stack protector GCC moves char arrays away from other locals. The page also leaves out variable-length arrays, new[] / delete[] and malloc, arrays of structs, pointer-to-array types like int (*p)[4], const char* literals in read-only memory, wide and UTF-8 strings, strcat, strcmp, and std::array, std::vector and std::string in detail. The byte values were checked with a small C program on arm64 and x86-64, built without size checks.

On the mind map

Open the Operating Systems mind mapOperatingSystemsBoot and program start: from power on to main()Boot and program startProcesses and the kernel: how user code talks to the kernelProcesses and the kernelInterrupts and devices: hardware interrupts the CPUInterrupts and devicesScheduling and deadlock: who runs next, who gets whatScheduling and deadlockVirtual memory: every address is translatedVirtual memoryPhysical memory: who gets which bytes of RAMPhysical memoryFiles and storage: from open() down to the diskFiles and storageDisks and RAID: blocks down to platter or flashDisks and RAIDIsolation and security: limit what a process can doIsolation and securityStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofArrays and C-stringsa[i] = base + i·sizeofRule of threeRule of threeOwn a pointer? Write dtor, copy, assignStruct paddingStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault backOpen the Operating Systems mind mapOperating Systemswho gets which bytes of RAMPhysical memoryStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofArrays and C-stringsa[i] = base + i·sizeofRule of threeRule of threeOwn a pointer? Write dtor, copy, assignStruct paddingStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault back
This page on the Operating Systems mind map · 66 pages in 9 branches · open it to see the whole map and test yourself in recall mode.