[英]Reverse String recursively in C with return and a putBack function
[英]How to recursively return string value in C?
嘗試在這里學習一些東西,而不是解決特定的問題。 請幫助我制定一些適用於這種情況的最佳做法,並在可能的情況下澄清原因。 提前感謝你的幫助。
基本上,我是在已知范圍內強行破解一個非常簡單的哈希算法。 函數針對散列測試字符串(在長度限制內)的可能性,直到它與傳遞的散列匹配為止。 然后,遞歸應停止所有迭代並返回匹配的字符串。 迭代是可行的 ,但是當找到答案時, 函數的每次運行似乎都沒有獲得通過調用同一函數返回的值 。
這是該函數的代碼,為清楚起見還帶有其他注釋:
//'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
從指針的一點點回想起,我猜想這是傳遞引用而不是值的東西,但是我沒有足夠的知識來解決它。 我已經閱讀了該線程 ,但是此建議似乎無法解決問題-我嘗試使用strcpy並獲得了相同的結果。
免責聲明:這是哈佛大學在EDX於2018年發布的CS50中的一項練習。 它不會影響我的評分(本周已經提交了兩個完美的練習,這是必需的),但是如上所述,我希望學習。
編輯 :將標簽編輯回C(如注釋中所闡明,字符串來自string.h,append由我編碼並經過多次驗證-我將在一段時間內進入TDD)。 謝謝大家的評論; 問題解決和經驗教訓!
我在代碼中發現了一個錯誤,但是我不確定這是否是您問題的根本原因。
代碼上線時:
strcmp(hash,force)==0
然后將“ test”指向的字符串分配給“ cracked”:
cracked = test;
然后點擊以下行:
if(cracked){break;}
然后循環就中斷了,下一行:
free(test);
該行將釋放測試指向的字符串,並記住它與'cracked'指向的字符串相同,因此您返回了一個已經釋放的字符串 。
該字符串將發生什么情況取決於您的編譯器和libc。 您可以嘗試通過為“破解”分配內存來解決此問題:
cracked = strdup(test);
此外,還有由“測試”和“強制”字符串引起的內存泄漏,但它們與您的問題無關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.