Search code examples
assemblyarmargumentsprintfargv

How to print argv arguments?


.global main

main:
    ldr r0, =message_format
    b   printf

message_format:
    .asciz "argv: %s\n"

If I execute it I got this:

# ./a.out 7
argv: ^?~^?~

How can I "pass" to printf my argv ?


Solution

  • argv is a pointer to a list of length argc + 1 of pointers to argument strings, where the last element is a NULL pointer.

    ldr r1, [r1,#4] will load the second element of argv (argv[1]) to r1. This is a pointer to the first argument string after the program name. (generally)

    You're passing this string pointer to printf as an integer, which is incorrect, and would lead to it printing what seems to be an arbitrary value.

    All argv elements are strings, so there is no additional transformation necessary. You just need to tell printf to expect a string instead of an integer, by changing the "%i" to a "%s".


    Note that this is only valid if you are sure that there is a second element. You should always check that argv[0] is non-NULL or that argc is greater than 0 before accessing argv[1]. You should then also check that argv[1] is non-NULL or that argc is greater than 1 before accessing the string pointed to by argv[1].