Since I use a pointer variable to iterate through the RAM addresses, this means the pointer variable itself is eventually also overwritten. A side effect I haven't considered until now.
So, I checked the RAM in fceux: When resetting the game and after fceux itself sets everything to $00 and $FF, I simply fill everything with the character X. Then I check which parts are overwritten with 0 by my code.
For some reason, the whole RAM still gets set to 0. There isn't a chunk of Xs anywhere in the code because of pointer misalignment or something like that, nor does the game run into an infinite loop because of the pointer's high byte value always being set back to 0.
I can set the pointer to any arbitrary address and it always worked.
Why is that the case? Why doesn't the below code produce chunks of RAM that remain untouched?
Code: Select all
; The value to
; write into RAM.
LDA #0
; The X and Y registers are
; used as counters for the
; loops and initialized with 0.
TAX
TAY
; Pointer + 0 always remains 0.
; The address is calculated
; by Pointer + 1 and by Y.
STA Pointer + 0
STA Pointer + 1
@initializeRamLoop:
; Set the value of 0
; to the current address.
STA (Pointer), Y
; Increment the low byte part
; of the address.
INY
; If it is set back to 0,
; increment the high byte part
; and, of course, the counter.
; Otherwise, continue with
; the inner loop.
BNE @initializeRamLoop
INC Pointer + 1
INX
; The outer loop ends
; just before address $0800.
CPX #$08
BNE @initializeRamLoop
; Set the pointer itself
; to 0 as well.
; Pointer + 0
; is always 0. So, we only
; need to set
; Pointer + 1.
; A is still 0 from above.
STA Pointer + 1
; The RAM has now been
; initialized with all zeroes.