VelocerOpen the app

Velocer › Flashcards › University of Wisconsin–Madison › CS 354: Machine Organization and Programming · UW-Madison

CS 354: Machine Organization and Programming · UW-Madison

Machine organization and programming review cards. went through the lecture topics week by week. · by proof_by_coffee · 205 cards

University of Wisconsin–Madison

Study this deck Embed

  1. Why can an ArrayList outperform a LinkedList on real hardware despite worse asymptotic complexity?ArrayList stores elements in contiguous memory, enabling CPU prefetching and cache-line spatial locality; LinkedList nodes are scattered on the heap, causing frequent cache misses and pointer-chasing overhead.
  2. What is spatial locality and why does it matter for performance?Spatial locality is the tendency to access memory locations near recently accessed ones. Contiguous data lets cache lines and the hardware prefetcher load adjacent values in one transaction, avoiding slow DRAM access.
  3. Roughly how do L1 cache and DRAM latencies compare?L1 cache access is about 1 ns, while DRAM access is about 80 ns—an ~80x difference that makes cache misses very costly.
  4. What does javac produce from Java source code?Platform-independent Java bytecode stored in .class files, which the JVM interprets and JIT-compiles to native machine instructions.
  5. What is the role of the JVM's Just-In-Time (JIT) compiler?It translates frequently executed (hot) bytecode paths into native machine instructions at runtime for faster execution.
  6. What is the C compilation pipeline from source to executable?gcc compiles .c to target-specific assembly (.s), assembles it into relocatable object code (.o), and the linker produces an ELF executable containing x86-64 machine code.
  7. Which Linux commands show your current directory and list all files including hidden ones?pwd prints the working directory; ls -la lists all files including dotfiles with permissions and sizes.
  8. What does the scp command do?It securely copies files between a local machine and a remote host, e.g. scp source user@host:dest.
  9. What is the difference between rm -rf and gio trash?rm -rf recursively deletes without confirmation and is permanent; gio trash moves files to the trash so they can be recovered.
  10. What are the basic vim mode commands for inserting text and saving/quitting?Press i for Insert mode, Esc for Normal mode, and :wq to save and quit.
  11. Why is the -Wall flag important when compiling C?It enables standard compiler warnings, which matter because C compilers otherwise permit dangerous implicit casts and uninitialized reads without complaint.
  12. Which values are falsy in classic C?Integer 0, floating-point 0.0, the null character '\0' (ASCII 0), and the NULL pointer. All non-zero values are true—including -1 and the character '0' (ASCII 48).
  13. What is the classic pitfall of writing if (money = 0) in C?It is an assignment, not a comparison: it sets money to 0 and evaluates to 0 (false). Use == for comparison.
  14. What do the printf specifiers %d, %u, %ld, %x, %p, and %s print?%d signed int, %u unsigned int, %ld signed long (64-bit), %x hexadecimal integer, %p pointer/address, %s null-terminated C-string.
  15. What does sizeof(arr) return for a local stack array int arr[6], and how do you compute the element count?It returns 24 (6 × sizeof(int)) because sizeof is evaluated at compile time. Element count is sizeof(arr) / sizeof(arr[0]).
  16. What happens to sizeof when an array is passed to a function like void foo(int a[])?The array decays into a raw pointer (int*), so sizeof(a) returns 8—the size of a 64-bit address—not the array's byte size.
  17. Does C perform runtime bounds checking on arrays, and do arrays store their length?No. C performs zero runtime bounds checking and arrays have no .length field; out-of-bounds writes silently corrupt adjacent memory or cause a segmentation fault.
  18. What happens when a C program writes past the end of a stack array?It silently overwrites adjacent stack variables or saved frame metadata, or triggers a Segmentation Fault (SIGSEGV) if it crosses into an unmapped or protected page.
  19. What is a C-string?A sequence of characters terminated by the null character '\0' (ASCII 0), which marks the end of the string.
  20. What character terminates a C-string, and what is its integer value?The null byte '\0', which has integer value 0.
  21. How do strlen(s) and sizeof(s) differ for a stack char array?strlen scans byte-by-byte until '\0' (O(N), excluding the null byte), while sizeof returns the compile-time byte capacity of the array.
  22. What happens if a C-string is missing its null terminator?strlen and printf("%s", s) read past the buffer into adjacent memory until they hit a random zero byte.
  23. Why is gets(buf) unsafe, and what should be used instead?gets performs an unbounded write that can cause buffer overflow; use fgets(buf, sizeof(buf), stdin) or a width-limited scanf like scanf("%9s", buf) for a 10-byte buffer.
  24. What does the address-of operator &x return?The virtual memory address where variable x lives.
  25. What does the dereference operator *p do?It follows the address stored in p to read or modify the target memory location, e.g., *p = 42 mutates the pointed-to variable.
  26. Why is returning the address of a local stack variable a bug?When the function returns its stack frame is popped, and the next function call reuses that stack space, silently overwriting the value the pointer refers to.
  27. What are three reasons to allocate memory on the heap instead of the stack?Lifetime persistence after the creating function returns, runtime sizing/resizing (e.g., realloc), and larger capacity (heap can scale to gigabytes vs. a stack of typically ~8 MiB).
  28. Where are automatic local variables stored, and what is their lifetime?They are allocated on the stack, alive only during function execution, and scoped locally to the block.
  29. Where are global variables stored, and what is their lifetime?In the Data/BSS segment, alive for the entire program execution and visible across the file/program.
  30. How does a static local variable differ from an ordinary local variable?It is scoped locally to its function but stored in the Data/BSS segment, initialized only once at program startup, and retains its value across repeated function calls.
  31. What is stored in the .text and .rodata segments?.text holds read-only executable machine instructions; .rodata holds immutable string literals, so modifying one (e.g., s[0] = 'H') causes a segfault.
  32. What is the difference between the .data and .bss segments?​.data holds globals and static variables explicitly initialized to non-zero values at compile time; .bss holds uninitialized or zero-initialized globals and statics, automatically zeroed by the OS loader.
  33. In which direction does the heap grow, and where does it start?The heap starts just above .bss and grows upward toward higher addresses via malloc/calloc/realloc.
  34. What is the purpose of the reserved unmapped low memory at address 0x0?It traps NULL pointer dereferences (0x0) with a segmentation fault.
  35. In which direction does the stack grow, and how does it change as functions are called and return?The stack starts near the top of user space and grows downward toward lower addresses as functions are called (pushing frames), and shrinks upward as functions return.
  36. Under the 64-bit Linux LP64 model, what are the sizes of char, short, int, long, float, and double?char = 1 byte, short = 2 bytes, int = 4 bytes, long = 8 bytes, float = 4 bytes, double = 8 bytes.
  37. How large is any pointer type (char*, int*, void*, struct foo**) on a 64-bit architecture?All pointers are 8 bytes on a 64-bit architecture.
  38. For a multi-byte variable, which of its bytes does the address (&x) refer to?The address is always the smallest (lowest) memory address among the contiguous bytes the variable occupies.
  39. In little-endian storage, where is the least significant byte placed?The least significant byte (LSB) is stored at the lowest memory address, followed by the higher-order bytes.
  40. In big-endian storage, where is the most significant byte placed?The most significant byte (MSB) is stored at the lowest memory address, followed by the lower-order bytes.
  41. What does the array identifier ints evaluate to for int ints[5], and what does *ints evaluate to?ints evaluates to &ints[0] (address of element 0), and *ints evaluates to ints[0].
  42. How does the C compiler translate arr[i], and what other equivalent form compiles the same way?arr[i] is translated to *(arr + i); because addition is commutative, i[arr] also compiles to *(i + arr).
  43. If short* p = (short*)0x100, what is p + 3?p + 3 is 0x100 + 3 * 2 = 0x106, since pointer arithmetic scales by sizeof(short) = 2 bytes.
  44. If int* p = (int*)0x100, what is p + 3?p + 3 is 0x100 + 3 * 4 = 0x10C, since pointer arithmetic scales by sizeof(int) = 4 bytes.
  45. What does subtracting two pointers of the same type (p2 - p1) yield?It yields the number of elements of type T between them: ((long)p2 - (long)p1) / sizeof(T).
  46. How is a contiguous 2D array like int c[5][6] laid out in memory, and what is sizeof(c)?It is a single flat contiguous block in row-major order totaling 5 * 6 * 4 = 120 bytes, so sizeof(c) is 120.
  47. For int c[5][6], what are sizeof(c[1]) and sizeof(c[1][2])?sizeof(c[1]) is 6 * 4 = 24 bytes (one row of 6 ints), and sizeof(c[1][2]) is 4 bytes.
  48. For int c[5][6], what does c decay to and what is its scaling factor?c decays to a pointer to a 6-int row (int (*)[6]), with a scale factor of sizeof(int) * 6 = 24 bytes.
  49. Why must the column count be specified in a function signature like void process(int m[][6])?The compiler needs the number of columns (6) to compute the row stride i * 6 * 4 bytes when indexing.
  50. How is a heap array-of-pointers (int** a) allocated, and are its rows contiguous?An outer malloc(ROWS * sizeof(int*)) allocates an array of 8-byte pointers, and each a[i] = malloc(COLS * sizeof(int)) points to a separately allocated row; rows are not guaranteed to be contiguous.
  51. How must a heap array-of-pointers be deallocated?Free every row in a loop (for each i, free(a[i])) before calling free(a).
  52. What is ptr->field shorthand for?ptr->field is exact shorthand for (*ptr).field.
  53. State Rule 2 of struct alignment (external/tail alignment).The total sizeof(struct) must be a multiple of the largest alignment requirement among its fields, so arrays of the struct keep every element aligned.
  54. What is the size and layout of struct increasing { char c; short s; int i; }?c at offset 0 (1B), 1B padding at offset 1, s at offsets 2-3, i at offsets 4-7; total = 8 bytes (a multiple of 4).
  55. What is the size and layout of struct scrambled { short s; int i; char c; }?s at offsets 0-1, 2B padding at 2-3, i at offsets 4-7, c at offset 8, and 3B tail padding at 9-11; total = 12 bytes.
  56. Why does field ordering matter in a struct?Because padding depends on field order: reordering fields can change the amount of internal and tail padding and thus the total sizeof(struct).
  57. What does malloc(size_t size) do?Allocates size uninitialized bytes on the heap and returns a pointer to them, or NULL on failure.
  58. How does calloc differ from malloc?calloc(nmemb, size) allocates nmemb * size bytes and zero-initializes all of them, whereas malloc leaves memory uninitialized.
  59. What does realloc(ptr, new_size) do?Resizes an existing allocation in place if adjacent free space permits; otherwise it allocates a new block, copies the data, and frees the old block.
  60. Is free(NULL) safe, and what corrupts the heap?free(NULL) is a safe no-op. Double-freeing or freeing a non-heap or mid-block pointer corrupts the heap.
  61. What does strcmp(s1, s2) return when the strings are equal?It returns 0 when equal, < 0 if s1 < s2, and > 0 if s1 > s2.
  62. Why is if (s1 == s2) a pitfall for comparing strings?It compares memory addresses, not string contents. Use strcmp instead, and remember if (strcmp(s1, s2)) is true when strings differ.
  63. How many bytes must dest have before strcpy(dest, src)?At least strlen(src) + 1 bytes, since dest must already be allocated and large enough to hold the source plus the null terminator.
  64. How is a virtual address (VA) split for paging?Into a Virtual Page Number (VPN) in the upper bits and a Page Offset in the lower bits (e.g., 12 bits for 4096-byte pages).
  65. What does the MMU do during address translation?It translates the VPN into a Physical Page Number (PPN) using the page table while keeping the page offset unchanged to form the physical address.
  66. What is the Translation Lookaside Buffer (TLB)?A small, ultra-fast hardware cache inside the MMU that caches recent VPN-to-PPN translations so page table walks in RAM are rarely needed.
  67. Why are multi-level page tables used?They avoid allocating a giant flat array for all possible virtual pages by organizing page tables as a sparse tree allocated on demand.
  68. Name the four major benefits of virtual memory.1) Illusion of abundant contiguous memory, 2) process isolation and memory protection, 3) simplified linking and loading, 4) controlled sharing of read-only pages.
  69. What is the page size tradeoff?Small pages bloat page tables (high metadata overhead); huge pages waste space inside partially used pages (internal page fragmentation).
  70. What two goals must a dynamic memory allocator balance?Maximize throughput (operations per second) and memory utilization (payload bytes vs. total heap footprint).
  71. What strict constraint prevents an allocator from relocating allocated blocks?User C code holds raw pointers to block addresses and C lacks type-safe reference tracking, so the allocator can never relocate an already-allocated block.
  72. What alignment must returned payload pointers satisfy on 64-bit systems?16-byte double-word alignment (addresses divisible by 16, ending in hex digit 0).
  73. What is the size of a union?The size of its largest member (plus alignment), since all fields start at byte offset 0 and share the same memory space.
  74. Why can't you dereference or do pointer arithmetic on a void*?Because void has no size; you must first cast it to a concrete pointer type, e.g., *(int*)vptr or ((char*)vptr) + 4.
  75. Describe the First-Fit placement policy.Always scans from the beginning of the heap and selects the first free block with size >= needed. Fast for small requests but creates splinter fragments at the front.
  76. Describe the Next-Fit placement policy.Starts scanning from where the previous search left off (wrapping around). Very fast amortized O(1) throughput but worse memory utilization than First-Fit.
  77. Describe the Best-Fit placement policy.Exhaustively scans all free blocks and selects the smallest free block with size >= needed. Maximizes utilization at the cost of an O(N) full heap scan.
  78. What is internal fragmentation?Wasted space inside an allocated block, caused by the 4-byte header and rounding the requested payload up to a multiple of 16 bytes.
  79. What is external fragmentation?Aggregate free memory is sufficient for a request, but no single contiguous free block is large enough. Depends on future request patterns.
  80. What is false fragmentation?Two or more adjacent free blocks that could satisfy a request if merged but remain separate. Solved by coalescing.
  81. What is immediate coalescing in a free list allocator?Merging adjacent free blocks immediately inside every free() call. It is simple and prevents false fragmentation but can cause thrashing if a block is repeatedly allocated and freed.
  82. What is delayed (deferred) coalescing?Marking blocks free in O(1) without merging, and only coalescing the heap when a malloc() search fails to find a large enough block.
  83. How does an implicit free list link blocks?Every block, allocated and free, is linked implicitly by storing its size in its header, so next = (char*)hdr + size. Allocation scans all blocks in O(N_total).
  84. How does an explicit free list differ from an implicit free list?Free blocks store 8-byte pred and succ pointers in their unused payload, forming a doubly-linked list of only free blocks. Search time drops from O(N_total) to O(N_free).
  85. What are the tradeoffs of LIFO vs address-ordered explicit free lists?LIFO inserts newly freed blocks at the head (O(1) insertion, fast coalescing). Address-ordered keeps the list sorted by address (O(N_free) traversal on free) but achieves better memory utilization.
  86. What are segregated free lists?An array of explicit free lists partitioned by size classes (e.g., powers of 2). Production malloc implementations use this to approach best-fit utilization at O(1) speed.
  87. What is simple segregated storage?Pages are divided into fixed-size slots per size class, with no splitting or coalescing. It gives O(1) alloc/free but higher internal and external fragmentation.
  88. What are the mark and sweep phases of garbage collection?Mark: DFS/BFS reachability traversal from root pointers on the stack/globals. Sweep: reclaim unmarked heap objects.
  89. Why can't C reliably use exact garbage collection?Pointers can be cast to integers, obfuscated via arithmetic, or stored in untyped unions/void*. A conservative collector cannot tell whether a 64-bit value is a random long or a live pointer, nor safely move blocks to update disguised pointers.
  90. What is the purpose of the memory hierarchy?Each smaller, faster, costlier layer acts as a cache for the layer below it, bridging the latency gap between fast CPUs and slow main memory.
  91. What is temporal locality?If a memory address is referenced once, it is likely to be referenced again in the near future, such as a loop counter, accumulator, or instructions in a tight loop.
  92. What is spatial locality?If a memory address is referenced, nearby addresses within the same cache block will likely be referenced soon, such as sequential array elements fetched in one 64-byte line.
  93. Why does row-major 2D array traversal have a low miss rate?C stores 2D arrays in row-major order, so a[r][c] with inner loop over c has stride-1 access. The first read incurs one cold miss loading 16 elements, yielding 15 hits (6.25% miss rate).
  94. Why does column-major 2D array traversal cause many cache misses?Accessing a[r][c] with inner loop over r has stride-N. For large N, each read jumps to a different cache block that is evicted before the next column iteration returns, giving up to a 100% miss rate.
  95. What is a cold (compulsory) miss?A miss because a block has never been accessed before (the cache starts empty). It is unavoidable on first access unless hardware prefetching is used.
  96. What is a capacity miss?A miss that occurs because the program's active working set of blocks is larger than the total cache capacity C, so blocks are evicted even if the cache were fully associative.
  97. What is a conflict miss?A miss in direct-mapped or set-associative caches when multiple active blocks map to the same cache set and repeatedly evict each other (thrashing), even though other sets are empty.
  98. What does the cache parameter tuple (S, E, B, m) represent?S = number of sets (2^s), E = associativity (lines per set), B = block size in bytes (2^b), m = total address bits (address space = 2^m bytes).
  99. How is total data capacity C computed for a cache?C = S × E × B = 2^s × E × 2^b bytes. It counts only data payload bytes, excluding valid bits, dirty bits, and tag metadata.
  100. How are address bits partitioned in a cache?m = t + s + b: t tag bits (upper), s set index bits (middle), b block offset bits (lowest).
  101. Why does a cache use the middle bits (not the high-order MSB bits) as the set index?Using high-order bits would map a large contiguous memory region to the same set, causing massive conflict misses during sequential traversal while other sets sit idle. Middle bits make adjacent blocks map to consecutive sets, maximizing spatial locality.
  102. What is a direct-mapped cache?A cache with E = 1 and S = C/B, where every memory block maps to exactly one line in one set. It is simple and fast (one tag comparator, no replacement policy) but vulnerable to conflict thrashing.
  103. What is a fully associative cache?A cache with S = 1 (s = 0) and E = C/B, where a block can go in any line. It eliminates conflict misses entirely but requires C/B simultaneous tag comparators, practical only for tiny caches like TLBs.
  104. When a set of E lines is full on a miss, what replacement policies can be used?LRU (evict least recently used), LFU (evict least frequently used), or Random. If any line is invalid, fill an invalid line first.
  105. What is the LRU replacement policy?Least Recently Used: evicts the line whose most recent access occurred furthest in the past. It exploits temporal locality.
  106. What is write-through policy?On a write hit, immediately writes updated data to both the cache and the next lower memory level. Simple but generates heavy bus traffic on every store.
  107. What is write-back policy?On a write hit, updates data only in the cache line and sets a 1-bit dirty bit. The block is written back to lower memory only when the dirty line is evicted, reducing bus bandwidth.
  108. What is write-allocate (fetch-on-write)?On a write miss, loads the missed block from lower memory into the cache first, then performs a write hit on the cached line.
  109. What is no-write-allocate (write-around)?On a write miss, bypasses the cache and writes modified bytes directly to lower memory without loading the block into the cache.
  110. When does a cache hit occur?A hit occurs if and only if a line in the selected set has Valid == 1 and Line.Tag == Addr.Tag.
  111. How is the set index computed from an address?Set = (Addr >> b) mod S, where b is the block offset bits and S is the number of sets.
  112. In x86-64 assembly, which register holds the return value of a function?%rax
  113. Which registers are used for the first six integer arguments in x86-64 calling convention?%rdi, %rsi, %rdx, %rcx, %r8, %r9
  114. What is the difference between movq and leaq?movq copies data from memory or a register; leaq computes an address (pointer arithmetic) without accessing memory.
  115. What do the condition codes ZF, SF, OF, and CF stand for?Zero Flag, Sign Flag, Overflow Flag, Carry Flag.
  116. Which instructions typically set the condition codes?cmpq and testq (also many ALU instructions).
  117. What is the purpose of the call and ret instructions?call pushes the return address and jumps to a function; ret pops the return address and returns.
  118. What does pushq do to the stack pointer?It decrements %rsp by 8 and stores the operand at the new address.
  119. What is the role of %rsp and %rbp in stack frame management?%rsp is the stack pointer (top of stack); %rbp is the base/frame pointer (stable reference for local variables).
  120. What are Unix signals?Software interrupts delivered to a process to notify it of events (e.g., SIGINT, SIGSEGV).
  121. What signal is generated by pressing Ctrl+C?SIGINT (interrupt signal).
  122. What does SIGSEGV indicate?A segmentation fault, typically due to invalid memory access.
  123. How do you register a custom signal handler in Unix?Using the sigaction() system call.
  124. How can a process send a signal to another process?Using the kill() system call (or kill command).
  125. What is symbol resolution in linking?The process of matching each symbol reference to exactly one symbol definition (e.g., strong/weak global symbols).
  126. What is relocation in linking?Adjusting addresses in code and data so that references point to the correct runtime locations.
  127. What is the size of a char in bytes, and what alignment does it require?char is 1 byte and requires alignment of 1 (any address).
  128. What is the size and required alignment of a short?short is 2 bytes and must be aligned to a multiple of 2 (an even address).
  129. What is the size and required alignment of a float?float is 4 bytes and requires alignment to a multiple of 4.
  130. What is the size and required alignment of a long?long is 8 bytes and must be aligned to a multiple of 8.
  131. What is the size and required alignment of a double?double is 8 bytes and requires alignment to a multiple of 8.
  132. What is the size and required alignment of any pointer type (T* or void*)?A pointer is 8 bytes and must be aligned to a multiple of 8.
  133. When you add k to a char* pointer, how many bytes does the address change?It changes by 1 × k bytes, since sizeof(char) is 1.
  134. When you add k to an int* pointer, how many bytes does the address change?It changes by 4 × k bytes, since sizeof(int) is 4.
  135. When you add k to a double* pointer, how many bytes does the address change?It changes by 8 × k bytes, since sizeof(double) is 8.
  136. What is the general formula for the address delta of ptr + k for a pointer of type T*?The delta is sizeof(T) × k bytes.
  137. Which printf specifier is used for a char, and which for an unsigned char?%c for char and %hhu for unsigned char.
  138. Which printf specifier is used for a short?%hd.
  139. Which printf specifiers are used for int and unsigned int?%d for int, %u for unsigned int, and %x for hexadecimal output.
  140. Which printf specifier is used for a float?%f.
  141. Which printf specifiers are used for long and unsigned long?%ld for long, %lu for unsigned long, and %lx for hexadecimal.
  142. Which printf specifier is used for any pointer?%p.
  143. Why does pointer arithmetic scale by the size of the pointed-to type?Because ptr + k advances by k elements of type T, so the byte delta is sizeof(T) × k.
  144. For a stack-allocated 2D array int c[ROWS][COLS], what is the address formula for c[i][j]?Base(c) + (i × COLS + j) × sizeof(int)
  145. What is the type of the expression c for a 2D array int c[ROWS][COLS]?int (*)[COLS] — a pointer to a row (array of COLS ints).
  146. What is the scale factor when adding 1 to c (a row pointer) in int c[ROWS][COLS]?COLS × 4 bytes (i.e., sizeof of one full row of ints).
  147. What does the expression c + i represent for int c[ROWS][COLS]?The address of row i, equivalent to &c[i]; it is still a row pointer of type int (*)[COLS].
  148. What is the type of *(c + i) or c[i]?int* — a pointer to the first element of row i.
  149. What is the scale factor of + 1 for the expression c[i] (an element pointer)?4 bytes (sizeof(int)).
  150. What does *(c + i) equal in terms of element addresses?&c[i][0], the address of the first element in row i.
  151. What is the equivalence of *(c + i) + j?&c[i][j], the address of element (i, j), of type int*.
  152. What is the type of the expression *(*(c + i) + j)?int — it is the value stored at c[i][j].
  153. How do you express the value c[i][j] using pointer arithmetic?*(*(c + i) + j)
  154. Why does adding 1 to c differ from adding 1 to c[i]?c is a row pointer, so +1 skips a whole row (COLS × 4 bytes); c[i] is an int pointer, so +1 skips one int (4 bytes).
  155. What is the base address of a 2D array c equivalent to?&c[0][0], the address of the first element.
  156. In the address formula, why is i multiplied by COLS?Because rows are stored contiguously, so each row advances by COLS elements; i rows skip i × COLS ints.
  157. What does &c[i][j] equal in pointer-arithmetic form?*(c + i) + j
  158. What is the first step in computing struct size and field offsets?Initialize offset = 0 and max_align = 1.
  159. How is a field's primitive alignment A_k determined?A_k equals sizeof(f_k), or for a nested struct/array, the largest primitive alignment among its members.
  160. When is internal padding added before placing a field?When offset % A_k != 0; add P_int = A_k - (offset mod A_k) so offset becomes the next multiple of A_k.
  161. How much internal padding is added for a field with alignment A_k at a misaligned offset?P_int = A_k - (offset mod A_k).
  162. How is max_align updated for each field?max_align = max(max_align, A_k).
  163. After placing a field, how is offset advanced?offset += sizeof(f_k), placing the field at [offset .. offset + sizeof(f_k) - 1].
  164. What is external (tail) padding?Padding added after the last field so the total size is a multiple of max_align.
  165. When is tail padding applied?After the last field, if offset % max_align != 0, pad offset up to the next multiple of max_align.
  166. What value does the algorithm return as sizeof(struct S)?The final offset after applying external (tail) padding.
  167. In what order are fields processed in the algorithm?In declaration order.
  168. What determines the alignment of a nested struct or array field?The largest primitive alignment among its members.
  169. Why does a struct's total size need to be a multiple of max_align?So arrays of the struct keep every element properly aligned; tail padding enforces this.
  170. What does max_align represent in the algorithm?The maximum alignment requirement among all fields, used to compute tail padding.
  171. What happens if offset is already a multiple of A_k for a field?No internal padding is added; the field is placed directly at offset.
  172. What is the difference between internal and external padding?Internal padding aligns each field before placement; external (tail) padding rounds the total struct size up to a multiple of max_align.
  173. What is the formula for the number of sets S in a cache?S = 2^s, where s is the number of set index bits.
  174. What is the formula for the block size B in a cache?B = 2^b, where b is the number of block offset bits.
  175. What is the formula for total cache capacity C?C = S × E × B, where S is the number of sets, E is associativity, and B is block size.
  176. What is the formula for the tag size t in a cache with m-bit addresses?t = m − (s + b), where s is set index bits and b is block offset bits.
  177. How do you extract the block offset from an address?Block Offset = Addr & ((1 << b) − 1), which takes the lowest b bits.
  178. How do you extract the set index from an address?Set Index = (Addr >> b) & ((1 << s) − 1), which takes the next s bits after the block offset.
  179. How do you extract the tag from an address?Tag = Addr >> (s + b), which takes the upper bits above the set index and block offset.
  180. Given m=64, s=13, b=6, how many tag bits are there?t = 64 − (13 + 6) = 45 bits.
  181. If a cache has 8192 sets, how many set index bits are needed?s = log₂(8192) = 13 bits.
  182. If a cache block size is 64 bytes, how many block offset bits are needed?b = log₂(64) = 6 bits.
  183. What does the block offset field select within a cache block?It selects the specific byte within the block (offset from the block start).
  184. What does the set index field select in a set-associative cache?It selects which set (group of blocks/ways) the address maps to.
  185. What is the purpose of the tag field in a cache address?The tag identifies which memory block is stored in a cache line, allowing comparison to detect a hit.
  186. In C, which values are considered false in a boolean context?Only 0, 0.0, '\0', and NULL are false. Notably '0' (ASCII 48) and -1 are TRUE.
  187. What is the pitfall of writing if (x = 0) versus if (x = 3) in C?if (x = 0) assigns 0, so the condition is always false. if (x = 3) assigns 3, so the condition is always true.
  188. What does strcmp(a, b) return when the two strings are equal?It returns 0, which is false in C. So equality is tested with if (strcmp(a, b) == 0).
  189. Why is if (strcmp(a, b)) misleading when checking string equality?The condition is true when strcmp returns nonzero, meaning the strings are different. It executes when strings differ, not when they match.
  190. Why should you never use a == b to compare two C strings?a == b compares pointer addresses, not string contents. Use strcmp for content comparison.
  191. For char s[20] = "hi"; what are sizeof(s) and strlen(s)?sizeof(s) is 20 (compile-time array capacity), while strlen(s) is 2 (runtime character count before '\0').
  192. For char* p = s; where s is a char array, what is sizeof(p)?sizeof(p) is the pointer size, typically 8 on a 64-bit system, not the array length.
  193. On little-endian x86-64, how is 0x12345678 stored starting at address 0x100?The least significant byte is at the lowest address: 78 at 0x100, 56 at 0x101, 34 at 0x102, 12 at 0x103.
  194. Does endianness affect how char[] strings are stored in memory?No. Strings always store s[0] at the lowest address regardless of endianness; only multi-byte numbers are affected.
  195. What is (int*)0x100 + 2 compared to (char*)0x100 + 2?(int*)0x100 + 2 is 0x108 because it adds 2 × 4 bytes. (char*)0x100 + 2 is 0x102 because it adds 2 × 1 byte.
  196. In int c[5][2], what is (long)(c + 3) - (long)c?It is 3 × (2 × 4) = 24 bytes, since each row is 2 ints of 4 bytes each.
  197. In int c[5][2], what is (long)(*(c + 3) + 1) - (long)c?It is 24 + 1 × 4 = 28 bytes: row 3 offset plus one int element.
  198. Where do initialized global variables go in memory?They go in the .data segment.
  199. Where do uninitialized globals and static locals go?Uninitialized globals go in .bss; static locals go in .bss or .data depending on initialization.
  200. Where are local variables and function parameters stored?On the Stack.
  201. For int* p = malloc(8) inside main, where are p and *p stored?p itself is on the Stack, while the allocated memory *p is on the Heap.
  202. For row-major int a[R][C] with B-byte cache blocks, how many integers fit per block?K = B / 4 integers per block, since sizeof(int) = 4.
  203. What is the cache miss rate for stride-1 access in a row-major int array?Miss rate = 1/K, missing once every K accesses.
  204. What is the cache miss rate for stride-2 access?Miss rate = 2/K, missing once every K/2 accesses.
  205. When does a cache miss rate reach 100%?When the stride is at least K integers, or when accessing column-major on a large matrix.

Velocer is free: spaced repetition and your own cards from any document.

PDF to flashcards · Lecture to flashcards · Practice exam · Syllabus study plan · Anki import

More decks from University of Wisconsin–Madison