使用 chdir() 会导致分段错误
Using chdir() Causes Segmentation Fault
我正在编写一个批处理模拟器作为个人项目。我正在尝试使用 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
参数并改用该参数。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?