Overview
This lecture covers how data and memory are managed in assembly (specifically MIPS), including accessing global variables, working with 1D and 2D arrays, and understanding structs. Practical assembly code examples are given, and best practices for addressing and indexing memory are discussed.
Memory Access and Global Variables
- Assembly instructions cannot operate directly on memory; data must be loaded into registers first.
- To modify a global variable: load it into a register, perform the operation, and store it back to memory.
- MIPS uses the
.data
section for global variables and .text
section for code.
Allocating and Accessing Arrays
- The
.space
directive allocates uninitialized bytes; alignment must match the data type (e.g., .align 2
for 4-byte word alignment).
- Arrays can be initialized as:
.word 1,2,3
or .byte 'a','b'
.
- The address of array element i:
base_address + i * element_size
(e.g., bytes: add i; words: add i*4).
- In C,
sizeof(array) / sizeof(array[0])
gives the element count.
Loops and Indexing in Assembly
- C for-loops/while-loops should be simplified before translating to assembly.
- Loop counter is stored in a register, incremented each iteration.
- Use array indices; avoid pointer arithmetic for clarity and easier debugging.
2D Arrays and Memory Layout
- 2D arrays are stored as rows concatenated in 1D memory.
- To access element at row r, column c: offset =
(r * ncols + c) * element_size
.
- Translate nested loops from C to assembly using the same indexing logic.
Structs (Structures)
- Structs are like arrays with heterogeneous elements, each member at a fixed offset.
- Calculate offsets by summing sizes of prior members, considering alignment/padding.
- Access struct members by using their defined offsets from the struct's base address.
Key Terms & Definitions
- Register — Small, fast storage location inside the CPU used for computation.
- Global Variable — Variable defined outside functions, accessible throughout the program.
- Directive — Special instruction to the assembler, e.g.,
.data
, .text
, .align
.
- Array — Sequence of elements, accessed by index; stored contiguously in memory.
- Struct (Structure) — Composite data type with named members, possibly of different types.
- Alignment — Ensuring data types are stored at addresses suitable for their size.
Action Items / Next Steps
- Attend C revision sessions (see Moodle/Blackboard Collaborate for details).
- Practice translating C array and loop code to assembly.
- Review course website for comprehensive examples, especially on 2D arrays and structs.
- Prepare for next lecture on functions in MIPS assembly.