Question: I need to create a code that prints the position of a search string. My current output with this code is : Enter the search

I need to create a code that prints the position of a search string. My current output with this code is :
Enter the search string: o
Enter the Input string to search: hello world.
string found at position: 4
segmentation fault (core dumped)
The output should be:
Enter the search string: o
Enter the Input string to search: hello world.
string found at position: 4
string found at postion: 7
section .data
promptSearch db "Enter the search string: ",0
promptInput db "Enter the input string to search: ",0
searchFormat db "%999s",0
inputFormat db "%4999s",0
foundMsg db "String found at position: %d",10,0
notFoundMsg db "String not found", 10,0
section .bss
searchString resb 1000
inputString resb 5000
section .text
global main
extern printf
extern exit
extern strstr
extern scanf
main:
; Prompting user for the search string
mov rdi, promptSearch
xor rax, rax
call printf
; Reading search string
mov rdi, searchFormat
mov rsi, searchString
xor rax, rax ; Clear RAX before scanf
call scanf
; Prompting user for the input string
mov rdi, promptInput
xor rax, rax
call printf
; Reading input string
mov rdi, inputFormat
mov rsi, inputString
xor rax, rax ; Clear RAX before scanf
call scanf
search_loop:
; Searching for the search string in the input string
mov rdi, inputString
mov rsi, searchString
call strstr
test rax, rax
jz search_not_found
search_found:
; Calculating the position of the found substring
sub rax, inputString
mov rsi, rax
; Printing message for found string
mov rdi, foundMsg
xor rax, rax
call printf
; Update inputString to point to the character after the last found occurrence
add rsi, 1 ; Move inputString pointer to the next character
add rsi, rax ; Move inputString pointer to the character after the last found occurrence
; Check if we've reached the end of the input string
cmp byte [rsi],0
je end
; Continue searching if there is more input to search
jmp search_loop
search_not_found:
; Printing message for not found
mov rdi, notFoundMsg
xor rax, rax
call printf
end:
; Exiting the program
mov rdi, 0
call exit

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!