I'm having trouble storing an integer into an array of strings using sprintf(). I am trying to create a new argv list to pass into my child process. I have 'curr' storing the correct value since I've tested in in GDB. My code is as follows:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h> /* for pid_t */
int main(int argc, char *argv[]){
static char *argv2[] = {"./datagen", "10", "outputfile", "SIGUSR1"};
pid_t pid = fork();
int curr = getpid();
sprintf(argv2[4], "%s", curr);
if(pid == 0)
{
printf("You are in the child process.\n");
}
else{
printf("You are in the parent process. Process ID is %d\n", getpid());
}
return;
}
After exhaustively searching around for a clear answer, I have yet to find anything. Ideally, the 4th slot of argv2 will store the process id as a string. However, I am getting a segmentation fault 11. If anyone could shed some light on this issue I would be eternally grateful.
Thank you!!
char buf[sizeof curr * CHAR_BIT/3 + 3]; sprintf(buf, "%d", curr);