【问题标题】:crypt(3) causing segmentation faultcrypt(3) 导致分段错误
【发布时间】:2016-06-22 12:58:47
【问题描述】:

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

【问题讨论】:

  • 哪一行显示调试器?
  • 由于我是 C++ 新手,我还没有调试器,但我发现它发生在:hash = crypt(line.c_str(), "");
  • 在对 crypt() 的调用中为第二个参数指定一个实际字符串是否可以修复它?
  • @Paradoxis:值得一读man page for crypt,因为它准确地指定了您需要为第二个参数(盐)传递的内容。
  • @Paradoxis 哦,哈哈,我只是猜到了。无论如何,不​​客气。我想我可以发布一个关闭的答案:3。

标签: c++ segmentation-fault crypt


【解决方案1】:

crypt() 调用的第二个参数(盐)接受一个字符串。您应该传递一个至少包含 2 个字符的字符串才能处理(如the manual)。 例如:crypt(line.c_str(), "Any string here");

【讨论】:

    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2012-02-20
    • 2011-11-06
    • 2020-12-31
    • 2019-07-21
    • 2018-07-28
    • 2014-04-25
    • 2011-07-18
    相关资源
    最近更新 更多