Regarding the execvp() function which takes in the string of the program to run and the array of strings of the arguments for that program (with the first string being the name of the program), I know we can just create a static array by doing char* args[] = {"arg1", "arg2" , NULL}, but what if we wanted to make it dynamic since we don't how large the array needs to be until runtime when I pass in a number specifying the arg count. I figured I could just create and pass in a 2d array dynamically to exec, but then when would I free that array since no code can run after the exec call?
A solution would be to make the static array sufficiently large where we can just overwrite the values, but its inefficient to do so wasting that much space.
You may be considering using an array allocated dynamically, and reallocating entries on a scheduled basis. Let's say we want to get the argument list from the standard input, and call
execvpwith a dynamically created array.I have created a pseudo object that has a
char **datafield, the count of allocated entries for the arguments, and the actualsize_t capacityfield that allows us to check how many elements it still can handle without having to be reallocated.This will read the program name from the standard input, will allocate strings, calling
strdup()for each argument andrealloc()when the array has to be reallocated to hold more elements, and it builds an array of strings (quasy optimun size, but speed efficient, by no calling realloc each time a new string has to be added) suitable to be given toexecvp().Of course, after you are finished, you must iterate all entries
free()ing them and finallyfree()thedataelement of the structure.Each reallocation normally forces the
realloc()routine to copy the array to a new place, if the memory allocated cannot be resized, and this is very inefficient, in case you need to reallocate every time you add a new element. For that reason, thecapacityfield allows to batch reallocations and do them only once perCAPACITY_INCREMENTadditions.