Search code examples
c++execvp

C++ Custom Shell Periodic Bad Address


Just to elaborate on the title, I am getting very perodic, random bad addresses when execvp() is called.

I can echo, use nano, cd, and every once in a while I will be hit with a bad address.

I am using a vector of strings, changing the vector of strings to a const char **, and appending null at the end. It seems as if null is not always getting read.

Any help is appreciated.

Code for reference:

int parse::sh_execute()
{
        const char **argv = new const char* [tokens.size()+1];
        for (int i = 0; i < tokens.size(); ++i)
        {
                argv[i] = tokens[i].c_str();
        }

        argv[tokens.size()+1] = NULL;


        pid_t pid, wpid;
        pid = fork();
        int status;


        if (pid < 0)
        {
                perror("fork error");
                exit(EXIT_FAILURE);
        }
        else if(pid == 0)
        {
                //child process
                if(execvp(argv[0], (char **)argv)== -1)
                {
                        perror("Child process error" );
                }
                exit(EXIT_FAILURE);
        }
        else
        {
                do
                {
                  wpid = waitpid(pid, &status, WUNTRACED);
                }
                while (!WIFEXITED(status) && !WIFSIGNALED(status));
        }
        return 1;

}

    int parse::sh_cd()
{
        if (tokens.size() == 1)
        {
                std::cout << "Error: No argument for cd" << std::endl;

        }
        else
        {
                int rc = chdir(tokens[1].c_str());
                if (rc < 0)
                {
                        printf ("Error changing directory: %s\n",strerror(errno));
                }
        }
        return 1;
}

Solution

  • N.M. Pointed out an accidental buffer overrun. Thanks.