Javant Javant - 1 year ago 40
C++ Question

Why am I segfaulting in this specific code?

This program is supposed to take a file name and argument(s) and create a process that executes the code while outputting the result to the terminal (which I don't know why that isn't working either).

I have found that the seg fault is coming from my attempt to free the argvNew array of strings

#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/wait.h>


main(int argc, char **argv){
int pid;
int i;
char *argvNew[argc-1];

do{
//Check for failure
if ((pid = fork()) < 0) {
cerr << "Fork error\n";
exit(1);
}
//Check if parent
else if (pid == 0) {
/* child process */

//Add arguments to new array
for(i = 0; i < argc-2; i++){
argvNew[i] = argv[i+1];
}
argvNew[argc-2] = NULL;

if (execvp(argv[1], argvNew) < 0) {
cerr << "Execve error\n";
exit(1);
}
}

else {
/* parent */
waitpid(pid, NULL, 0);/* wait for the child to finish */

//Free argvNew
for(i = 0; i < argc-1;i++){
free(argvNew[i]);
}
free(argvNew);
}

//if we're need to create a new list of args in the future put it here
}while(!argc);
}


test input:
./myProgram /bin/ls -l

Answer Source

argvNew is automaticlly allocated, which means that the resources held by it are released automagiclly when it goes out of scope. You only need to free dynamicly allocated arrays:

char a[50]; // the [50] means automatic allocation
// ...
// no need to free

char* a = malloc(50); // dynamic allocation
// ...
// need to free later, or memory leak
free(a);