使用 chdir() 会导致分段错误

Using chdir() Causes Segmentation Fault

本文关键字:分段 错误 chdir 使用      更新时间:2023-10-16

我正在编写一个批处理模拟器作为个人项目。我正在尝试使用 unistd.h 中的 chdir() 实现 cd 命令。但是,使用此方法会导致段错误。

主.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);
}

奇怪的是,使用 cout 获取 chdir 的路径工作得很好。我该如何解决这个问题?

代码中有递归的、未终止的行为。这会溢出堆栈。

尝试在void chdir(std::string path)中插入断点,看看会发生什么。

你会看到函数chdir调用自己,然后又一次又一次地调用自己,嗯,分段错误。

另外,尝试查看调试器中的"调用堆栈"是什么,这个问题在那里非常明显。

你应该使用

::chdir(path.c_str());

或者您将再次调用自己的方法。

在unistd.h中,chdir被定义为:

int chdir(const char *);

因此,您必须使用 const char* 参数调用它,否则编译器将搜索另一个名为"chdir"的函数,该函数采用std::string参数并改用该参数。