我从运行此代码得到以下错误:
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1074==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x00000042acda (pc 0x000000422519 bp 0x7ffe697712d0 sp 0x7ffe697711f0 T1074)
==1074==The signal is caused by a WRITE memory access.
#0 0x422518 (/root/sandbox/crack+0x422518)
#1 0x7fb78fc7ab96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#2 0x402a79 (/root/sandbox/crack+0x402a79)
UndefinedBehaviorSanitizer can not provide additional info.
==1074==ABORTING
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <crypt.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
string hash = argv[1];
string salt = "AB";
for (int i = 0; i < 2; i++)
{
salt[i] = hash[i]; // The error is here.
}
printf("%s\n", salt);
}
else
{
printf("ERROR\nUsage: ./crack hash\n");
return 1;
}
}
经过研究,我知道您不能将一个数组中的字符分配为另一个数组中的字符,但是当我尝试时:
int j = hash[i]; // It worked here.
salt[i] = j; // The error is here.
它仍然没有用。有人可以帮我解决这个问题吗?我需要将命令行参数中的前两个字符存储为它们自己的变量。
最佳答案
您使用CS50库和头文件。在string.h
中,string
被定义为char*
。 string salt = "AB";
定义一个指向文字字符串的指针。文字字符串是常量,不能修改。您需要一个字符数组,例如:
char salt[3];
另外,不要忘记在循环之后在字符串的末尾粘贴一个0:
salt[i] = 0;
否则,您的字符串将不会终止。更好的是,调用函数
strncpy
而不是编写自己的循环:strncpy(salt, hash, (sizeof salt) - 1);