Counting Characters in a String in armV7

风流意气都作罢 提交于 2021-01-28 19:44:23

问题


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

回答1:


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:

  • Prompting the user to enter a string
  • Setting up r0, r1, and r2 to utilize fgets (pay particular attention to the use of loading the value of FILE* stdin into r2)
  • Calculating the length of the string and chopping off the newline
  • Printing the result

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.



来源:https://stackoverflow.com/questions/61847657/counting-characters-in-a-string-in-armv7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!