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.

3
  • 4
    Why don't you show us what you've tried instead of telling? Commented Apr 19, 2012 at 7:36
  • 2
    Most likely you are trying to modify a string literal through the pointer causing an Undefined Behavior and the crash. Commented Apr 19, 2012 at 7: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. Commented Apr 19, 2012 at 7:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You're right, I didn't read the question carefully enough the first time. Sample code updated.

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.