LC-3汇编代码Bug排查:列表最大值查找功能异常求助
Let's break down this common bug and how to fix it in a single line. First, let's assume your original buggy code looks like this (super typical for this problem with the missing critical piece):
; Original buggy code ; Assume R2 is preloaded with the list start address (e.g., x4000) LOOP LDR R3, R2, #0 ; Load current element into R3 BRn END_LOOP ; Exit if we hit the negative sentinel ; Compare R3 to current "max" in R5 NOT R4, R5 ADD R4, R4, #1 ; R4 = -R5 ADD R4, R3, R4 ; R4 = R3 - R5 BRnz SKIP_UPDATE ; Skip if R3 isn't larger than current max ADD R5, R3, #0 ; Update max to R3 SKIP_UPDATE ADD R2, R2, #1 ; Move to next element BR LOOP END_LOOP HALT
The Root Bug
Your code never initializes R5 with the first element of the list! When the program starts, R5 holds a random garbage value (whatever was left in that register from prior execution). So even if the first element is the actual maximum, your comparison logic might ignore it because it's comparing against meaningless data.
The One-Line Fix
Add this line right before the LOOP label to initialize R5 with the first valid element of the list:
LDR R5, R2, #0 ; ✅ Added line: Set initial max to the first list element
To make the flow fully correct (so we don't reprocess the first element), you'll also want to increment R2 immediately after this line (though technically, this is a second line—but if we're being strict, the core fix is the initialization of R5; the increment is just cleanup for proper loop flow). Here's the full fixed code:
; Fixed code ; R2 is preloaded with list start address LDR R5, R2, #0 ; ✅ Critical initialization line ADD R2, R2, #1 ; Move to next element to avoid reprocessing LOOP LDR R3, R2, #0 ; Load current element into R3 BRn END_LOOP ; Exit if we hit the negative sentinel ; Compare R3 to current max in R5 NOT R4, R5 ADD R4, R4, #1 ; R4 = -R5 ADD R4, R3, R4 ; R4 = R3 - R5 BRnz SKIP_UPDATE ; Skip if R3 isn't larger than current max ADD R5, R3, #0 ; Update max to R3 SKIP_UPDATE ADD R2, R2, #1 ; Move to next element BR LOOP END_LOOP HALT
Why This Works
By loading the first element into R5 upfront, you give your comparison logic a valid starting point. Now every subsequent element is compared against the actual first value (not garbage), and the max gets updated correctly as you iterate through the list.
Testing with your example:
- R2 starts at x4000
- We load x4000's value (5) into R5 first
- Increment R2 to x4001
- Next element is 1: 1 < 5, so no update
- Next element is -1: exit loop, R5 holds 5 (correct!)
内容的提问来源于stack exchange,提问作者Jeffrey Beaucage

