x86架构NASM代码复制字节时遇无效有效地址错误求助
Fixing "Invalid effective address" in NASM for x86 Hex Digit Copy
Got it, let's break down why you're running into that "Invalid effective address" error and get your hex digit copy working correctly.
The Root of the Problem
x86 assembly has strict rules for effective memory addresses—you can't just use ax directly as an index into an array like you would in C. Here are the two key issues with your original approach:
- x86 doesn't allow
axas a base or index register for memory addressing. Only registers likebx,si,di,bp(and their 32-bit counterparts if you're in 32-bit mode) are valid for this. - You can't do a direct memory-to-memory
movinstruction—you need to use a general-purpose register as a middleman to hold the byte you're copying.
The Solution
Let's rewrite the code step by step to fix both issues:
First, here's your data section for reference:
section .data hex_digits: db '0123456789abcdef' ; 16 hex characters, indexes 0-15 hex_out: db '0000' ; 4-byte string, indexes 0-3
Now, in your text section, here's how to safely copy hex_digits[ax] to hex_out[3]:
section .text global _start _start: ; Let's say ax already holds your target index (e.g., 0x05 for '5') mov ax, 0x05 ; Step 1: Move ax's value to a valid index register (bx here) mov bx, ax ; Step 2: Load the byte from hex_digits[bx] into al (8-bit register, since we're dealing with a single byte) mov al, [hex_digits + bx] ; Step 3: Store the byte from al into hex_out[3] (hex_out + 3 is the memory address of the 4th character) mov [hex_out + 3], al ; Optional: Add code to print hex_out or exit cleanly here ; ...
Key Notes
- Valid Index Registers: If you prefer, you could use
siordiinstead ofbx—all three are valid for base/index addressing in x86. - Range Check: Since
hex_digitsonly has 16 elements (indexes 0-15), make sureaxis between 0 and 15 before doing the copy. Ifaxis larger, you'll access memory outside your array, which can cause crashes or unexpected behavior. - Memory-to-Memory Restriction: Remember, x86
movcan't transfer directly from one memory location to another—always use a register as an intermediary.
内容的提问来源于stack exchange,提问作者Jacob Garby
相关产品推荐
相关产品推荐

