Using chdir() Causes Segmentation Fault

1.2k views Asked by At

I'm writing a batch emulator as a personal project. I'm trying to implement the cd command using chdir() from unistd.h. However, using this causes a segfault.

main.cpp:

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>

//Custom headers
#include "splitting_algorithm.hpp"
#include "lowercase.hpp"
#include "chdir.hpp"

//Used to get and print the current working directory
#define GetCurrentDir getcwd

using namespace std;

int main(int argc, char* argv[])
{
    string command;

    //Begin REPL code
    while (true)
    {
        //Prints current working directory
        cout<<cCurrentPath<<": ";

        std::getline(std::cin, command);

        vector<string> tempCommand = strSplitter(command, " ");

        string lowerCommand = makeLowercase(string(strSplitter(command, " ")[0]));

        //Help text
        if(tempCommand.size()==2 && string(tempCommand[1])=="/?")
        {
            cout<<helpText(lowerCommand);
        }

        //Exit command
        else if(lowerCommand=="exit")
        {
            return 0;
        }
        else if(lowerCommand=="chdir")
        {
            cout<<string(tempCommand[1])<<endl;
            chdir(tempCommand[1]);
        }

        else
            cout<<"Can't recognize \'"<<string(tempCommand[0])<<"\' as an internal or external command, or batch script."<<endl;
    }
    return 0;
}

chdir.cpp:

#include <cstdlib>
#include <string>
#include <unistd.h>

void chdir(std::string path)
{
    //Changes the current working directory to path
    chdir(path);
}

Strangely enough, using cout to get the path for chdir works perfectly fine. How do I fix this?

2

There are 2 answers

0
riodoro1 On BEST ANSWER

You have recursive, unterminated behaviour in Your code. This overflows the stack.

Try to insert breakpoint in void chdir(std::string path) and see what happens.

You will see that the function chdir calls itself, and in turn calls itself again, and again and... well, segmentation fault.

Also, try to see what "call stack" is in the debugger, this issue is very visible there.

0
helb On

You should invoke the underlying chdir function using

::chdir(path.c_str());

or you will just call your own method again.

In unistd.h, chdir is defined as:

int chdir(const char *);

So you must call it with a const char* argument or the compiler will search for another function called "chdir" which take a std::string argument and use that instead.