DMG-01
DMG-01 copied to clipboard
Potential panic in memory bus code due to off-by-one error
This code here defines memory
to be 0xFFFF
(65535) long, which means you have 0-65534
as a usable range. If you address index 0xFFFF
(65535) here, it will panic since that is 1 more than the length we defined. And according to the manuals I read, 0xFFFF
is technically a valid addressable part of memory. So the length should be 0x10000
(65536; 0-65535
which makes 0xFFFF
addressable) instead of 0xFFFF
.
This also has the nice benefit of letting rust optimize out the bounds check.
struct MemoryBus {
memory: [u8; 0xFFFF]
}
impl MemoryBus {
fn read_byte(&self, address: u16) -> u8 {
self.memory[address as usize]
}
}
(And for example, in this chapter, it says "(0xFFFF or 65,536 of them to be exact)", but 0xFFFF
is 65535 not 65536)
https://rylev.github.io/DMG-01/public/book/cpu/executing_instructions.html