到达主C++之前分段故障
Segmentation Fault before reaching main - C++
我正在编写代码来查找适当的输入,该输入将为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之前的分段错误"来搜索此问题的解决方案,这篇文章似乎正在经历类似的问题: 主节点之前的分段错误
但是,我已经研究了两个建议的解决方案,但找不到适合我的解决方案。
我认为我的代码在堆栈中没有太多变量。事实上,为了以防万一,我已经尝试使用该函数
sha1()
注释掉,但发生了同样的问题。在使用之前,我已经初始化了代码中的所有
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>
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串
- 面临分段故障 使用 ffmpeg 读取视频时,因为"pFormatCtx-> streams [i]-> codecpar"的地址0x00
- 在C++中,当指向删除和指向不同对象时,分段故障指针
- 分段故障说明
- 分段故障(核心转储)-不知道为什么
- 分段故障线程
- hiredis SET遇到分段故障
- 分段故障,合并排序算法
- 多线程程序中的分段故障和gdb回溯上的不完整信息
- 到达主C++之前分段故障
- 分段故障核心使用 IF流转储
- 使用向量的移动键盘排列(分段故障)
- 在二进制树插入和遍历期间,我得到了分段故障
- 分段故障在类之间返回整数
- C++分段故障BST