【发布时间】:2019-10-10 14:23:17
【问题描述】:
我正在编写一个代码来找到一个合适的输入,该输入将为 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 before segmentation fault”来寻找解决此问题的方法,而这篇文章似乎遇到了类似的问题:@987654322 @
但是,我研究了两种建议的解决方案,但找不到适合我的解决方案。
我认为我的代码在堆栈中没有太多变量。其实我也试过用函数
sha1()注释掉以防万一,但还是出现了同样的问题。在使用前我已经在我的代码中初始化了所有
char*和std::string。
仅供参考,我正在使用 g++ 编译我的 C++ 代码。
我们将不胜感激任何帮助或推动正确方向。
【问题讨论】:
-
您的代码不需要使用任何
char *变量。一切都可以std::string,因此更安全。 -
@PaulMcKenzie 是对的,您应该非常谨慎对待使用遗留 C 字符串的 C++ 代码。并不是说您不能,只是如果您只编写 C++ 代码,这很少是一个好主意。
-
@paxdiablo 感谢您的提醒,但下面的答案(我仍在尝试在脑海中处理)说字符串文字无法修改。似乎遗留的 C 字符串更容易编码但不安全......? (我知道它们不安全,因为我在使用它们时遇到了太多错误。我只想知道我在正确的页面上)
-
C 风格的字符串更难处理,而不是更容易!您必须管理它们的生命周期和容量,而
std::string则不需要。 -
如果你打开了编译器警告,编译器本身就会指出代码中的错误。
标签: c++ string segmentation-fault undefined-behavior string-literals