地穴(3)导致分割故障

crypt(3) causing segmentation fault

本文关键字:分割 故障 地穴      更新时间:2023-10-16

我正在尝试制作一个小程序来打开文件,读取每一行,使用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;
}

呼叫crypt()(盐)的第二个参数取一个字符串。您应该传递一个至少2个字符的字符串,以便使用它(如手册中)。例如:crypt(line.c_str(), "Any string here");