0

I have this code that works (it's a bit stripped down):

char *parmList[6];

parmList[0] ="/root/ssl_send";
parmList[1] ="-m 1";            
...etc...
parmList[5] = NULL;
execvp(parmList[0], parmList);

Now I want to write something to one string in this list with sprintf (it's more correct to say that I want that one pointer of *parmList[6] points to a char array constructed with sprintf). I am getting "Segmentation errors" all the time. I have tried:

  • using malloc,
  • declaring a double array so the memory space is reserved,
  • using snprintf,....

I am obviously doing something wrong. The problem is similliar to Sprintf Segmentation Fault, just that I need to have a list of pointers/char_arrays for execvp.

Community
  • 1
  • 1
  • 4
    Why don't you **show** us what you've tried instead of telling? – littleadv Apr 19 '12 at 07:36
  • 2
    Most likely you are trying to modify a string literal through the pointer causing an Undefined Behavior and the crash. – Alok Save Apr 19 '12 at 07:37
  • 1
    String literals are typically read-only and it's UB to try and write to them. If you want to modify these then you need to allocate memory for them and copy the string literal data. – Paul R Apr 19 '12 at 07:37

1 Answers1

1

Here is code that uses sprintf to create a string and uses that string in your argument list. Make sure you allocate enough space for the sprintf output.

char *parmList[6];
parmList[0] = "/bin/ls";
char arg1[10];
sprintf(arg1, "%s", "-l");
parmList[1] = arg1;
parmList[2] = NULL;
execvp(parmList[0], parmList);
Ivo Bosticky
  • 6,338
  • 6
  • 34
  • 35