1

I am trying to use execvp to execute unix commands with given flags.

My array, argv, might contain these elements:

{"ls", "-a"}

I am then passing this array to

execvp(argv[0], argv);

How can I safely append NULL onto the end of the argv array so execvp will know where to terminate?

3
  • 1
    Is the array statically defined, or is it passed to the program as an argument, or are you generating it from user input? Commented Sep 8, 2015 at 0:28
  • If he’s taking in a non-NULL-terminated array with no extra room, he’ll have to copy it to an array one element larger, but that’s unlikely? Commented Sep 8, 2015 at 0:40
  • Thanks for the responses. I was indeed generating it off of user input. As I mentioned below, it was an oversight on my end. I forgot to account for the NULL element when calling malloc. Commented Sep 8, 2015 at 0:46

1 Answer 1

1

You have 2 elements in your array. Simply allocate three elements instead and set the last one to NULL:

char* args[] = {"ls", "-a", NULL};
execvp(path, args);

Or, since you mention malloc():

char** args = malloc(3 * sizeof args[0]);
args[0] = "ls";
args[1] = "-a";
args[2] = NULL;
execvp(path, args);
free(args);
Sign up to request clarification or add additional context in comments.

5 Comments

You don't need to cast malloc() return in C
We do not know if the array that needs modification is allocated by him or something else.
If he wants to extend an existing array that he did not allocate himself, he will have to allocate a new array and copy the existing values into it.
It turns out this was simply an oversight on my end. Thank you for the responses. Since I am generating the array based off of user input, I am using a counter variable that matches the amount of commands and/or flags. When calling malloc() I forgot to account for extra element of NULL.
I know, it's nitpicking, but since beginners copy code, i want to mention that malloc could return NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.