为什么我会收到未定义的行为准则:死亡信号?CS50 Pset2裂纹

为什么我会收到未定义的行为准则:死亡信号?CS50 Pset2裂纹,c,undefined-behavior,cs50,C,Undefined Behavior,Cs50,我在运行时而不是编译时遇到此错误。我隔离了导致错误的行44(删除它可以避免错误)。下面给出了代码片段和错误消息 根据我的研究,错误信息表明我正在试图写入我不应该访问的部分内存。对于另一个问题,我做了类似的事情:将字符串从main传递到函数,编辑函数中字符串中的一些字符,然后将该字符串返回到另一个变量。我尝试将返回的字符串分配给一个新变量,但仍然出现错误。我能做些什么来理解并避免将来出现这种错误 #include <cs50.h> #include <stdio.h> #i

我在运行时而不是编译时遇到此错误。我隔离了导致错误的行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;
}
这是无效的。
字符串键
指向字符串文本
“a”
。字符串文本
“A”
是不可变的,不能修改,而
crypt
需要一个指向7字节缓冲区的有效指针(至少)

做:

这是无效的。
字符串键
指向字符串文本
“a”
。字符串文本
“A”
是不可变的,不能修改,而
crypt
需要一个指向7字节缓冲区的有效指针(至少)

做:


谢谢!现在我可以变异字符数组中的字符了。非常感谢!现在我可以在这个字符数组中对字符进行变异。
$ ./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
string key = "A";
crypt(key, ...);
char key[7];
crypt(key, ....);