简体   繁体   中英

crypt function in C breaking password string in for loop

I am new to C, and I have been going through the CS50 course to learn some basics. I have been trying to solve the challenge which requires you to make a simple password cracker, but I ran into a problem which prevents me from writing a function program: every time I call the crypt function in my for loop, it somehow breaks my password string that I am iterating through.

I have tried making a copy of the password string, and passing that as an argument to crypt; I have also tried moving the crypt call into a separate function and calling that from the loop (as well as the combination of the two)

#define _XOPEN_SOURCE
#include <unistd.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>

string buildLetterDictionary();

int main(int argc, string argv[])
{
    if (argc == 2)
   {
        printf("Two arguments, starting test...\n");

        char password[2];
        string letters = buildLetterDictionary();
        for(int i = 0; i < 5; i++)
        {
            password[0] = letters[i];
            password[1] = '\0';
            printf("Password: %s\n", password);
            string hashed = crypt(password, "50");
            printf("\n%i\nOriginal: %s\nHashed: %s\n", i, password, hashed);
        }
        return 0;
    }
    else
    {
        printf("Usage: ./crack hash");
        return 1;
    }
}

string buildLetterDictionary()
{
    char letters[27];
    for(int i = 65; i < 91; i++)
    {
        letters[i-65] = i;
    }
    letters[26] = '\0';
    string letter = letters;
    return letter;
}

if I comment out the lines:

string hashed = crypt(password, "50");
printf("\n%i\nOriginal: %s\nHashed: %s\n", i, password, hashed);

The code works as expected, and produces the output:

A
B
C
D
E

But if I leave those lines in, the password is printed out as 'A' with the hash "50pe4e2XTIS/g" the first time, but every subsequent time is printed out as "" with the hash "50sXZPq5euCxs"

Please let me know what the underlying problem is, so that I may work towards resolving it! Thanks for any help in advance!

I am guessing here that cs50.h contains some definitions like a type alias from char * to string that the professor is giving you for simplicity.

If that is true, then buildLetterDictionary() cannot work, because you are doing:

char letters[27];
...
char * letter = letters;
return letter;

This means you are returning the address of a local variable, which will be destroyed as soon as you leave the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM