Skip to content

Potential panic in memory bus code due to off-by-one error #73

Description

@MolotovCherry

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions