Reputation: 55
This is my code to concatenate two strings in NASM. I got a segmentation fault core dumped error. So i started commenting to find the source of the error. As you can see in the code I used %ifdef
and %endif
to create block of comment. When I excluded the line "jmp l1" from comment, it gave a segmentation fault. Could someone help me by telling me why jmp is giving segmentation fault?
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
Upvotes: 0
Views: 1020
Reputation: 134005
Most likely, the problem is that the string doesn't contain a carriage return character (ASCII value 13).
After each failed check (i.e. cmp al, 13
), the ECX
register is incremented and the jmp l1
instruction creates a loop. So you're going through the string looking for the value 13, but if 13 doesn't exist in the string the loop never terminates. At some point you try to access memory that your process does not have permissions to access. Thus the seg fault.
Most likely what you need is a terminating condition that will stop the loop if you reach the end of the string, which is probably a null character (value 0). Something like:
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
(For the nitpickers: I realize that there are faster ways of checking for al==0
. I chose cmp
because it's more clear, and easier for a beginner to understand.)
Upvotes: 1