c - Copy argv to another variable to change it without change the original -


my program has variable number of args , need make execv new path, want change value of argv[1] in different variable without changing it, won't let me.

char** arg_exec = malloc(argc * sizeof (char*)); int i; for(i=0;i <= argc-1; i++)    arg_exec[i] = strdup(argv[i]); arg_exec[argc] = null; if( (pid = fork()) == 0){     arg_exec[1] = strcat(directory , dir_info->d_name); //some variables current path , name     execv(arg_exec[0], arg_exec);     printf("error in process %d\n", getpid());     return 1;  } 

but after runs line arg_exec[1] = strcat(directory , dir_info->d_name); changes value of argv[1], , program fails..

it worked fine execl, since execl(argv[0],strcat(directory , dir_info->d_name), ..., null); because have variable number of arguments run it, wouldn't implement way.

edit1: added null @ end of array edit2: i'm doing version of find, strcat add current directory folder into. initalization of directory: char *directory = strcat(argv[1],"/");

char *directory = strcat(argv[1],"/"); attemps modify argv[1] beyond allocation, ub. @alk.

modifying argv may ub. is argv[n] writable?

so allocate memory both.

note: char** arg_exec = malloc(argc * sizeof (char*)); insufficient argv[argc] must null. need 1 more. notice argc not passed execv().


step 1. make copy of pointer array argv[]

char **argv_new; size_t a_size = sizeof *argv_new * (argc + 1);  // + 1 final null argv_new = malloc(a_size); memcpy(argv_new, argv, a_size); 

step 2. form new arg[1]

int size = 1 + snprintf(null, 0, "%s/%s", argv[1], dir_info->d_name); argv_new[1] = malloc(size); snprintf(argv_new[1], size, "%s/%s", argv[1], dir_info->d_name); 

use it

execv(arg_new[0], arg_new); free(argv_new[1]); free(argv_new); 

tbd: error checking add for: argc > 1, malloc(), snprintf(), execv()


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -