Reputation: 238
I have made a program that takes a string as a input from user and then calculates its length and display it. But I am getting an error Segmentation fault (core dumped)
when I run the program. My code is shown below
str_len: ;Procedure to calculate length of String
xor rdx,rdx
xor rcx,rcx ;I want to store length in rcx
mov rdx,[string] ;string contains the input taken from the user
mov rsi,rdx
mov rcx,'0' ;By default rcx will contain '0' decimal
up: cmp byte[rsi],0 ;Compare if end of string
je str_o ;If yes then jump to str_o
inc rcx ;Increment rcx i.e., length
inc rsi ;Point to next location of rdx i.e.,string
jmp up ;Repeat till end of string
str_o: mov rax,1 ;Print final length
mov rdi,1
mov rsi,rcx
mov rdx,1
syscall
ret
I can guarantee that rest of my program is correct. The error will be in the above part of the code. What is probably the error ?
Upvotes: 0
Views: 895
Reputation: 29022
The error is here:
mov rdx,[string] ; string contains the input taken from the user
You are loading RDX with the first 8 bytes of the string content and not the address of the string. So better use
lea rdx, string ; LEA = Load Effective Address
Another problem is that your output routine tries to print a number that is not converted to ASCII with
mov rax,1 ; SYS_WRITE - Print final length
mov rdi,1 ; STDOUT handle
mov rsi,rcx ; RSI should point to buffer
mov rdx,1 ; length of buffer - a value of one prints only one char
syscall
This doesn't work that way. You'd have to convert the qword number in RCX to an ASCII string before and then pass the address of this string in RSI. Search Stack Overflow for questions like this.
Upvotes: 2