Isaac Wasserman
Isaac Wasserman

Reputation: 83

Execve() adds two extra arguments

When I compile the following code and run strace on it, I can see that it adds two additional elements to the args[] array.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char *args[2];
    args[0] = "/bin/ls";
    args[1] = "-lh";
    execve(args[0], args, NULL);

    return 1;
}

strace says that this is what is actually being called:

execve("/bin/ls", ["/bin/ls", "-lh", "\340\301\361\267", "\1"], NULL)

Upvotes: 1

Views: 388

Answers (1)

Pablo Yaggi
Pablo Yaggi

Reputation: 1231

You need to add a null ptr to the last element of the argument array. Otherwise execve doesn't know where your array ends.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char *args[3];
    args[0] = "/bin/ls";
    args[1] = "-lh";
    args[2] = NULL;
    execve(args[0], args, NULL);

    return 1;
}

So basically what you are seeing is execv passing random arguments until it found a NULL in the memory you point with the array. Of course it could be crashing as well.

Upvotes: 2

Related Questions