BETA Try the new lesson view
Theory

Extra: how does the CPU see it?

Extra. Not graded. What do a struct, malloc and free look like to the processor?

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

A struct's fields are offsets

In memory, an IntArray is 16 bytes: data (a pointer, 8 bytes), then count and capacity (4 each). The processor doesn't know a field's name, only its offset from the start of the struct:

  • m->data is [rax] (offset 0);
  • m->count is 8[rax];
  • m->capacity is 12[rax].

m->count is two steps, as in topic 8: first the pointer m is taken, then the value 8 bytes further on is read.

What to notice (-O0)

  • realloc, malloc and free are plain calls, like your own functions. realloc gets the old address in rcx and the size in bytes in rdx (new_capacity · 4, lea rdx, 0[0+rax*4]), and returns the new address in rax.
  • if (new_data == NULL) is a comparison with 0 right after the call.
  • The heap itself is not in the assembly, only calls. What is allocated, how much and when is known only while the program runs, so the compiler can't see a leak and AddressSanitizer can.

Switch to -O1: array_init shrinks to a few writes, and m stays in a register instead of being read from memory for every field.