【发布时间】:2019-02-01 13:32:40
【问题描述】:
尝试在这里学习一些东西,而不是解决特定问题。请帮助我找到一些适用于这种情况的最佳实践,并在可能的情况下澄清原因。提前感谢您的帮助。
基本上,我在已知范围内暴力破解了一个非常简单的哈希算法。函数根据散列测试字符串(在长度限制内)的可能性,直到它与传递的散列匹配。然后递归应该停止所有迭代并返回匹配的字符串。迭代是有效的,但是当找到答案时,似乎函数的每次运行都没有得到相同函数调用返回的值。
这是函数的代码,为了清楚起见,额外添加了 cmets:
//'hash' is the hash to be replicated
//'leading' is for recursive iteration (1st call should have leading=="")
//'limit' is the maximum string length to be tested
string crack(string hash, string leading, int limit)
{
string cracked=NULL, force=NULL, test=NULL;
//as per definition of C's crypt function - validated
char salt[3] = {hash[0], hash[1], '\0'};
// iterate letters of the alphabet - validated
for(char c='A'; c<='z'; c++)
{
// append c at the end of string 'leading' - validated
test = append(leading,c);
// apply hash function to tested string - validated
force = crypt(test,salt);
// if hash replicated, store answer in 'cracked' - validated
if(strcmp(hash,force)==0)
{
cracked = test;
}
else
{
// if within length limit, iterate next character - validated
if(strlen(test)<=limit+1)
{
// THIS IS WHERE THE PROBLEM OCCURS
// value received when solution found
// is always empty string ("", not NULL)
// tried replacing this with strcpy, same result
cracked = crack_des(hash,test,limit);
}
}
// if answer found, break out of loop - validated
if(cracked){break;}
// test only alphabetic characters - validated
if(c=='Z'){c='a' - 1;}
}
free(test);
// return NULL if not cracked to continue iteration on level below
// this has something to do with the problem
return cracked;
} // end of function
从我对指针的记忆中,我猜这是传递引用而不是值的东西,但我没有足够的知识来解决它。我已阅读 this thread,但此建议似乎无法解决问题 - 我尝试使用 strcpy 并得到相同的结果。
免责声明:这是 EDX 哈佛大学 2018 年 CS50 中的一项练习。它不会影响我的评分(本周已经提交了两个完美的练习,这是必需的)但如上所述,我正在学习。
编辑:将标签编辑回 C(如 cmets 中所述,字符串来自 string.h,并且 append 由我编码并多次验证 - 我将在一会儿)。谢谢大家的cmets;问题解决了,吸取了教训!
【问题讨论】:
-
有人在我不看的时候给 C 添加了字符串类型吗?还是 char* 的 typedef?
-
你是说C++? C中没有
string。 -
...据我所知,在 C++ 中的
bool上下文中没有用于转换的运算符,因此如果意图是 C++,if(cracked){break;}是可疑的。代码中的所有内容似乎都与它是一个 typdef 一致。 -
将
c标签更改为c++。append()方法不是 C 方法。这是一个 C++ 方法。 -
修复提交,使其中有递归函数。了解如何定义
string和append也会有所帮助。