Question

I am trying to read a number from the user and then read it using the read() system call. I am eventually going to be using the terminal in raw mode so I need to use read() and not scanf(). Here is what I am doing:

readAndStore:
    /*Read input*/
    mov     r0, #0  /*Set to read from std in*/
    mov     r1, sp  
    mov     r2, #1  
    bl      read
    /*Check whether the number is between 1 and 5 */
    ldr     r1, [sp]
    sub     r0, r1, #0x30  /*For example if '2' is entered: 0x32 - 0x30 = 2  */
    cmp     r0, #1
    bge     second  /* If greater than or equal, to go to second  */
    mov     r0, #1  /*If less than 1, return 1 */
    b       return
second: 
    sub     r0, r1, #0x30
    cmp     r0, #7
    ble     store    /* If less than or equal to 7, go to store */
    mov     r0, #1   /* If not, return 1 */
store:
    /*Code to store result*/

    mov     r0, #0    /*Return 0 if input is valid (between 1-5)*/
return: 
    pop     {fp, lr}d
    mov     sp, fp
    bx lr

I use a loop in main that keeps calling this readAndStore method until it returns 0 (Meaning input is valid).

Here is the output I get when I run my program:

Choose a number: 2   /* I enter number 2 */
Choose a number: Choose a number: 

Here is another example:

Choose a number: 22   /* I enter number 22 */
Choose a number: Choose a number: Choose a number: 

Basically it just prints n+1 number of input prompt strings. My prediction is that the problem is what I am putting into r2 immediately before I call read but I am not sure. Any ideas what I am doing wrong?

Était-ce utile?

La solution

You are calling read for a single character, but then you use

ldr     r1, [sp]

This will load a whole 32-bit word. Your stack will contain "random" data, making 24-bit of r1 random.

You should use

ldrb     r1, [sp]

instead. Also you have to make sure that you allocate space on the stack for this value.

There are also some other missing parts in the code, you don't check for the upper boundary (0x39) on the read value. The code will always return 0, as the mov r0, #1 is always superseded by the mov r0, #0 in "store:"

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top