到达主C++之前分段故障

Segmentation Fault before reaching main - C++

本文关键字:分段 故障 C++      更新时间:2023-10-16

我正在编写代码来查找适当的输入,该输入将为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之前的分段错误"来搜索此问题的解决方案,这篇文章似乎正在经历类似的问题: 主节点之前的分段错误

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

  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++中具有常量字符数组的类型,任何修改字符串文本的尝试都会导致未定义的行为。 您正在尝试至少在此语句中修改字符串文字:

strncpy(prefix, hashvalue.c_str(), 8);

您应该使用字符数组或类型为std::string的对象,而不是字符串文字。

注意这一点;例如,这个if语句

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

可以写得更简单:

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

虽然看起来条件没有意义。也许你的意思是以下内容

while ( hashvalue.size() > 1 ) {

您还需要包含标头<string>

#include <string>