NASM 中的 JMP 指令给出分段错误

JMP instruction in NASM gives segmentation fault

这是我在 NASM 中连接两个字符串的代码。我收到分段错误核心转储错误。所以我开始评论以找到错误的来源。正如您在代码中看到的,我使用 %ifdef%endif 来创建注释块。当我从评论中排除行 "jmp l1" 时,它给出了分段错误。有人可以告诉我为什么 jmp 会出现分段错误吗?

extern scanf
extern printf

section .bss
str1: resb 20
str2: resb 10

section .data
msg1: db "Enter data:",0

msg2: db "%s",0
msg3: db "You entered %s",10,0

msg4: db "%s",0

test: db "Test",0

section .text
global main
main:
push msg1
call printf
add esp,4

push str1
push msg4
call scanf
add esp,8

push msg1
call printf
add esp,4

push str2
push msg4
call scanf
add esp,8


mov ecx,0
mov edx,0
l1:
mov al,byte[str1+ecx]

cmp al,13

je next

inc ecx
%ifdef
jmp l1

next:cmp byte[str2+edx],13
je finish
mov al,byte[str2+edx]
mov byte[str1+ecx],al
inc ecx
inc edx
jmp next

finish:
%endif
next:
push str1
push msg3
call printf
add esp,8

mov eax,1
mov ebx,0
int 80h

问题很可能是字符串不包含回车 return 字符(ASCII 值 13)。

每次检查失败后(即 cmp al, 13),ECX 寄存器递增并且 jmp l1 指令创建一个循环。因此,您正在遍历字符串以查找值 13,但如果字符串中不存在 13,则循环永远不会终止。在某些时候,您尝试访问您的进程无权访问的内存。因此段错误。

很可能您需要的是一个终止条件,如果您到达字符串的末尾,它会停止循环,这可能是一个空字符(值 0)。类似于:

l1:
mov al,byte[str1+ecx]
cmp al,13
je next
; added next two lines to check for end of string
cmp al,0   ; if the value is 0, at end of string
je notFound

inc ecx
jmp l1

(对于吹毛求疵的人:我发现检查 al==0 的方法更快。我选择 cmp 因为它更清晰,初学者也更容易理解。)