为什么我会在此特定代码中进行分类?

时间:2016-08-30 23:19:02

标签: c++

该程序应该采用文件名和参数,并创建一个执行代码的过程,同时将结果输出到终端(我不知道为什么它也不起作用)。

我发现seg错误来自我试图释放argvNew字符串数组

#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);
}

测试输入:./myProgram /bin/ls -l

2 个答案:

答案 0 :(得分:3)

argvNew 自动分配,这意味着当它超出范围时,它所拥有的资源会自动释放。您只需free动态分配数组:

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);

答案 1 :(得分:-1)

for(i = 0; i < argc-1;i++){
    free(argvNew[i]);
}
//This next call is identical to free(argvNew[0]), probably where you're 
//segfaulting, since you're freeing something twice
free(argvNew);

请注意,您不需要调用free(),因为argvNew []包含的指针不指向new / malloc的数据,而是指向由父级管理的argv数组的值。过程,不应该由你明确地自由()