为什么我会收到UndefinedBehaviorSanitizer:DEADLYSIGNAL? CS50 Pset2破解

我在运行时未编译时收到此错误。我隔离了导致错误的行,该行是44(删除它可以避免该错误)。代码段和错误消息如下。

根据我的研究,错误消息表明我正在尝试写入不应访问的部分内存。对于另一个问题,我做了类似的事情:将字符串从main传递给函数,在函数内的字符串中编辑一些字符,然后将该字符串返回到另一个变量。我尝试将返回的字符串分配给新变量,但仍然出现错误。将来如何做才能理解和避免此错误?

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <crypt.h>

string get_nextkey(string currentkey);
int get_nextchar(char current);

string starters[5] = {"A","AA","AAA","AAAA","AAAAA"};

int main(int argc,string argv[])
{
    if (argc == 2)
    {
        string hash = argv[1];
        char salt[3];
        salt[0] = hash[0];
        salt[1] = hash[1];
        salt[2] = '\0';
        printf("%lu %s\n",strlen(salt),salt);
        string key = "A";
        for (int i = 0; i < 100; i++)
        {
            printf("testing key: %s\n",key);
            string keyhash = crypt(key,salt);
            if (strcmp(hash,keyhash) == 0)
            {
                printf("%s\n",key);
                return 0;
            }
            key = get_nextkey(key);
        }     
    }
    printf("Usage: ./crack hash\n");
    return 1;
}

string get_nextkey(string currentkey)
{
    int length = strlen(currentkey);
    int nextchar = get_nextchar(currentkey[length-1]);
    if (nextchar != 0)
    {
        currentkey[length-1] = nextchar;
    }
    return currentkey;
}

int get_nextchar(char current)
{
    int nextchar = current + 1;
    if (nextchar < 123)
    {
        if (nextchar > 90 && nextchar < 97)
        {
            nextchar = 97;
        }
    }
    else
    {
        return 0;
    }
    return nextchar;
}
$ ./crack 50cI2vYkF0YU2
2 50
testing key: A
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1361==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x00000042b316 (pc 0x000000422b46 bp 0x7fff6b45cc20 sp 0x7fff6b45cb60 T1361)
==1361==The signal is caused by a WRITE memory access.
    #0 0x422b45  (/root/sandbox/crack+0x422b45)
    #1 0x422836  (/root/sandbox/crack+0x422836)
    #2 0x7f00a0281b96  (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #3 0x402b79  (/root/sandbox/crack+0x402b79)

UndefinedBehaviorSanitizer can not provide additional info.
==1361==ABORTING
to71229 回答:为什么我会收到UndefinedBehaviorSanitizer:DEADLYSIGNAL? CS50 Pset2破解

string key = "A";
crypt(key,...);

无效。 string key指向字符串文字"A"。字符串文字"A"是不可变的,不能被修改,而crypt则需要一个有效的指针(至少指向7个字节)。

要做:

char key[7];
crypt(key,....);
本文链接:https://www.f2er.com/3069445.html

大家都在问