Reputation: 11
My program is supposed to ask for a single line of user input and then print out the number of characters in the string. As of now it is telling me there are 104 characters when I input hello followed by a segmentation fault.
Here is my code:
userInput:
.asciz "\nEnter a string: "
TemptRet:
.word 10
inputBuffer:
.skip 11
countMessage:
.STRING "There are %d characters in: \"%s\".\n"
.text
.global main
main:
LDR R0, =courseStr
BL puts
countString:
LDR R0, =userInput
BL printf
LDR R0, =TemptRet
BL scanf
getLine:
MOV R2, R0
BL getchar
LDR R2, =inputBuffer
MOV R1, R0
LDR R0, =countMessage
BL printf
Upvotes: 1
Views: 1185
Reputation: 2440
A few suggestions.
Your use of scanf
to read in a string is going to stop at the first space in your input. Instead you can use fgets
which looks a bit more complicated but with understanding the ARM procedure calling convention is quite easy.
Second, move your .data
section to the end and start with push {ip, lr}
so your routine can end with pop {ip, pc}
.
Consider using comments in your assembly to understand what each line is doing. Writing in a high-level language without comments is bad enough, in assembly it is even easier to forget what you were doing.
There are several key sections to the code below:
fgets
(pay particular attention to the use of loading the value of FILE* stdin
into r2)input.s
:
.global main
main:
push {ip, lr}
ldr r0,=prompt // r0 <- prompt*
bl printf
ldr r0,=buffer // r0 <- buffer*
mov r1,#buflen // r1 <- buflen
ldr r2,=stdin
ldr r2,[r2] // r2 <- STDIN
bl fgets // fgets(buffer, buflen, STDIN)
bl strlen // r0 <- strlen(buffer)
mov r1,r0 // r1 <- strlen(buffer)
sub r1,#1 // r1 <- r1 - 1
ldr r0,=output // r0 <- output*
ldr r2,=buffer // r2 <- buffer*
mov r4,#0
str r4,[r2,r1] // r4(NULL) -> buffer + strlen
bl printf
pop {ip, pc}
.data
prompt:.asciz "Enter a string: "
output:.asciz "There are %d characters in: \"%s\".\n"
buffer:.space 128
buflen=.-buffer
pi@raspberrypi:~ $ gcc input.s -o input
pi@raspberrypi:~ $ ./input
Enter a string: this is a string of moderate length
There are 35 characters in: "this is a string of moderate length".
Good luck.
Upvotes: 1