[英]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. 我是C语言的新手,而且我一直在学习CS50课程,以学习一些基础知识。 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. 我一直在尝试解决要求您做一个简单的密码破解程序的挑战,但是遇到一个阻止我编写功能程序的问题:每次在for循环中调用crypt函数时,都会以某种方式破坏密码我正在遍历的字符串。
I have tried making a copy of the password string, and passing that as an argument to crypt; 我尝试过复制密码字符串,并将其作为参数传递给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) 我还尝试过将crypt调用移到一个单独的函数中,然后从循环中调用它(以及两者的结合)
#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" 但是,如果我保留这些行,则密码第一次以散列为“ 50pe4e2XTIS / g”的形式输出为'A',但随后的所有时间都以散列为“ 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. 我在这里猜测cs50.h
包含一些定义,例如从char *
到教授为简化起见而给出的string
的类型别名 。
If that is true, then buildLetterDictionary()
cannot work, because you are doing: 如果是这样,则buildLetterDictionary()
无法正常工作,因为您正在执行以下操作:
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. 这意味着您将返回一个局部变量的地址,该变量将在离开函数后立即销毁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.