gpt4 book ai didi

c++ - sha-1 c++ 中的堆栈检查失败

转载 作者:行者123 更新时间:2023-11-28 00:28:30 27 4
gpt4 key购买 nike

我在主线程中有一个 __stack_chk_fail。我不知道为什么会这样?

Stack Flow

我从这个网站得到代码: http://www.packetizer.com/security/sha1/
我正在尝试使用示例添加一个函数来计算文件的摘要。

.h文件

#include <stdio.h>
#include <string>
std::string digestFile( char *filename );

.cpp文件

std::string SHA1::digestFile( char *filename )
{
Reset();

FILE *fp = NULL;
if (!(fp = fopen(filename, "rb")))
{
printf("sha: unable to open file %s\n", filename);
return NULL;
}

char c = fgetc(fp);
while(!feof(fp))
{
Input(c);
c = fgetc(fp);
}

fclose(fp);

unsigned message_digest[5];
if (!Result(message_digest))
{ printf("sha: could not compute message digest for %s\n", filename); }

std::string hash;
for (int i = 0; i < 5; i++)
{
char buffer[8];
int count = sprintf(buffer, "%08x", message_digest[i]);
if (count != 8)
{ printf("converting unsiged to char ERROR"); }

hash.append(buffer);
}

return hash;
}

最佳答案

__stack_chk_fail 当您写入无效地址时发生。

事实证明你是这样的:

    char buffer[8];
int count = sprintf(buffer, "%08x", message_digest[i]);

C 字符串以 NUL 结尾。这意味着当 sprintf 写入 8 位数字时,它会添加 9-th char'\0'。但是 buffer 只有 8 个 char 的空间,所以第 9 个超出了缓冲区的末尾。

您需要 char buffer[9]。或者使用 std::stringstream 以 C++ 方式实现,它不涉及任何固定大小,因此没有缓冲区溢出的风险。

关于c++ - sha-1 c++ 中的堆栈检查失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23910934/

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