2016-06-22 15 views
0

私はC++にはかなり新しくなっています。C++のcrypt(3)がセグメント違反の原因となる

ファイルを開き、すべての行を読み込み、crypt(3)アルゴリズムを使用してその行をハッシュし、出力ファイルに書き戻す小さなプログラムを作成しようとしています。

しかし、私がcrypt()メソッドを使用しようとすると、セグメントエラーが発生します。誰かが私が間違っていることを教えてもらえますか?ありがとうございました。私は

コマンドコードをコンパイルするために使用した:

g++ hasher.cpp -o hasher -lcrypt 

マイコード:

#include <iostream> // User I/O 
#include <fstream> // File I/O 
#include <vector> // String array 
#include <cstdlib> // Exit method 
#include <crypt.h> // Crypt(3) 

// Input & Output file names 
std::string input_file; 
std::string output_file; 

// Plaintext & Hashed passwords 
std::vector<std::string> passwords; 


// Read input and output files 
void read_file_names() 
{ 

    std::cout << "Input: "; 
    std::getline(std::cin, input_file); 

    std::cout << "Output: "; 
    std::getline(std::cin, output_file); 
} 

// Load passwords from input file 
void load_passwords() 
{ 
    // Line/Hash declarations 
    std::string line; 
    std::string hash; 

    // Declare files 
    std::ifstream f_input; 
    std::ifstream f_output; 

    // Open files 
    f_input.open(input_file.c_str()); 


    // Check if file can be opened 
    if (!f_input) { 
     std::cout << "Failed to open " << input_file << " for reading." << std::endl; 
     std::exit(1); 
    } 

    // Read all lines from file 
    while(getline(f_input, line)) 
    { 
     // This line causes a segmentation fault 
     // I have no idea why 
     hash = crypt(line.c_str(), ""); 
     std::cout << "Hashed [" << hash << "] " << line << std::endl; 
    } 
} 

// Main entry point of the app 
int main() 
{ 
    read_file_names(); 
    load_passwords(); 
    return 0; 
} 
+0

デバッガはどの行に表示されますか? –

+0

私はC++を初めて使っているので、まだデバッガを持っていませんが、 'hash = crypt(line.c_str()、"); ' – Paradoxis

+0

' line.c_str '' crypt'の呼び出しのように見える?それは非NULLですか? 'crypt'を呼び出す直前に' std :: cout << "行:" << line.c_str()<< std :: endl; "を追加してみてください。また、gccを使用していて、デバッガを持っていれば、[gdb](http://www.cs.cmu.edu/%7Egilpin/tutorial/)と呼ばれることに注意してください。 –

答えて

1

のcrypt()の呼び出し(塩)の2番目のパラメータは文字列を指定します。あなたはそれが働くために2文字以上の文字列を渡すべきです(the manualのように)。 例:crypt(line.c_str(), "Any string here");

関連する問題