tags:

views:

50

answers:

1

Hi,

I am trying to do something quite easy: fill an char** with arguments I want to use in a execvp call in C.

This is how I am doing:

 if(argc >=1)
    {
      *nargv = "--action";
      while(argc--)
        {
          printf("nargv1 => %s \t argv1 => %s \n", *nargv, *argv);
          *++nargv = *argv++;
          printf("nargv2 => %s \t argv2 => %s \n", *nargv, *argv);
        }

      printf("nargv3 => %s \t argv3 => %s \n", *nargv, *argv);
      *nargv++ = '\0';
      printf("nargv4 => %s \t argv4 => %s \n", *nargv, *argv);
}

The output gives me:

nargv1 => --action       argv1 => backup
nargv2 => backup         argv2 => --help
nargv1 => backup         argv1 => --help
nargv2 => --help         argv2 => (null)
nargv3 => --help         argv3 => (null)
nargv4 => (null)         argv4 => (null)

This sounds ok (nargv is filled correctly, at least that's what I thought)> But when I do execvp("command",nargv) my arguments are not passed through. What's wrong ? I have tried to play with gdb with no success.

Regards

+5  A: 

Since you do ++nargv, your nargv pointer ends up pointing past the end of the array. Retain a pointer to the initial member and pass that to exec. Also, *nargv++ = '\0' looks like a bug, since you assign a char to a pointer to char.

Jouni K. Seppänen
Good catch for the '\0'. I will fix that.For the other part of your answer, could you show me some code to do that ? I did not get it :p thanx
Xavier Maillard
its' like this - if you start with p = top and loop p++ then at the end of the loop p will point at the *end* of the list, not the beginning. you need to pass the beginning i.e. top not p.
joefis
Alternatively, use array indexing: if you do *nargv++ you modify nargv, but if you do nargv[i++] you only modify the index i and can pass the intact nargv to exec.
Jouni K. Seppänen