gpt4 book ai didi

c++ - 到达主程序之前出现段错误 - C++

转载 作者:行者123 更新时间:2023-12-02 01:20:44 25 4
gpt4 key购买 nike

我正在编写代码来查找合适的输入,为 SHA-1 哈希函数生成特定的输出。

我遇到的问题是我的代码引发了段错误,但是 gdb 发现它在输入 main() 和执行之前引发了以下错误任何其他代码:

Program received signal SIGSEGV, Segmentation fault.
__strncpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:636
636 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or directory.

这是我的代码:

#include <iostream>
#include <cstdlib>
#include <cstring>

#include "sha1.hpp"

int main() {
char *prefix = "SHA1sha1";
char *suffix = "chicken and beer";
std::string hashvalue = "nonzero";
char *line = "just some dummy string";
int loop_number = 0;

while (hashvalue.c_str()[0] != '0' || hashvalue.c_str()[1] != '0') {
// change prefix
strncpy(prefix, hashvalue.c_str(), 8);
// hash the concatenated string of prefix and suffix
strncpy(line, prefix, 8);
strncat(line, suffix, strlen(suffix));
hashvalue = sha1(line);

loop_number++;
if (loop_number % 1000 == 0) std::cout << loop_number << "th loop, hash value: " << hashvalue << std::endl;
}

std::cout << "Found prefix: " << prefix << " with hash value: " << hashvalue << std::endl;

return 0;
}

sha1.hpp不是我实现的,而是从这里获取的:http://www.zedwood.com/article/cpp-sha1-function

不过,我已将 sha1.h 更改为 sha1.hpp,但这可能不是导致段错误的原因。

现在我已经尝试使用错误消息以及关键字“main之前的段错误”来搜索此问题的解决方案,并且这篇文章似乎遇到了类似的问题:Segmentation Fault before main

但是,我研究了两个建议的解决方案,但找不到适合我的解决方案。

  1. 我认为我的代码堆栈中没有太多变量。事实上,为了以防万一,我尝试过使用函数 sha1() 进行注释,但还是出现了同样的问题。

  2. 在使用之前,我已经初始化了代码中的所有 char*std::string

仅供引用,我正在使用 g++ 编译我的 C++ 代码。

任何帮助或插入正确的方向将不胜感激。

最佳答案

您正在修改不可变内容。

// change prefix
strncpy(prefix, hashvalue.c_str(), 8);
// hash the concatenated string of prefix and suffix
strncpy(line, prefix, 8);
strncat(line, suffix, strlen(suffix));

尝试按如下方式更改声明。

char prefix[100] = "SHA1sha1";
char suffix[200] = "chicken and beer";
char line[200] = "just some dummy string
<小时/>

另外,我想

while (hashvalue.c_str()[0] != '0' || hashvalue.c_str()[1] != '0') {

应该是

while (hashvalue.c_str()[0] != '0' && hashvalue.c_str()[1] != '0') {

更新:

德摩根定律规定,

not (A and B) = not A or not B

同样,使用他们想要的任何形式都是个人的选择

关于c++ - 到达主程序之前出现段错误 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58325178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com