-2

個人的なプロジェクトとしてバッチ エミュレーターを作成しています。unistd.h の chdir() を使用して cd コマンドを実装しようとしています。ただし、これを使用するとセグメンテーション違反が発生します。

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

奇妙なことに、cout を使用して chdir のパスを取得すると、問題なく動作します。これを修正するにはどうすればよいですか?

4

2 に答える 2

3

コードに再帰的で終了していない動作があります。これにより、スタックがオーバーフローします。

ブレークポイントを挿入してvoid chdir(std::string path)、何が起こるかを確認してください。

chdir関数が自分自身を呼び出し、次に自分自身を何度も呼び出していることがわかります...まあ、セグメンテーション違反です。

また、デバッガーで「コール スタック」が何であるかを確認してみてください。この問題は非常に目に見えます。

于 2015-06-18T07:11:16.060 に答える
2

を使用して、基になる chdir 関数を呼び出す必要があります。

::chdir(path.c_str());

または、独自のメソッドを再度呼び出すだけです。

unistd.h では、chdir は次のように定義されています。

int chdir(const char *);

したがって、引数を指定して呼び出す必要があります。そうしないとconst char*、コンパイラは引数を取り、代わりにそれを使用する「chdir」と呼ばれる別の関数を検索しstd::stringます。

于 2015-06-18T07:12:24.417 に答える