一系列問題。首先,正如templatetypedef所說的,你分配不足。
然後,就像稻田說的那樣,你不能釋放你的malloc'd內存。如果您需要Y=X
一行,則需要將原始malloc'd空格地址存儲在另一組變量中,以便您可以在其上調用free
。
...mallocs...
int * original_y = Y;
int * original_x = X;
...body of code...
free(original_y);
free(original_x);
return X[0];
但是這並沒有解決你的新問題,這就是爲什麼代碼不工作?我承認我不能遵循你的代碼(沒有更多的研究),但是我可以提出一種算法,它可以工作,而且更容易理解。這可能有點僞代碼並不是特別高效,但要正確的是第一步。我後來列出了一些優化。
int lcs(char * A, char * B)
{
int length_a = strlen(A);
int length_b = strlen(B);
// these hold the position in A of the longest common substring
int longest_found_length = 0;
// go through each substring of one of the strings (doesn't matter which, you could pick the shorter one if you want)
char * candidate_substring = malloc(sizeof(char) * length_a + 1);
for (int start_position = 0; start_position < length_a; start_position++) {
for (int end_position = start_position; end_position < length_a; end_position++) {
int substring_length = end_position - start_position + 1;
// make a null-terminated copy of the substring to look for in the other string
strncpy(candidate_substring, &(A[start_position]), substring_length);
if (strstr(B, candidate_substring) != NULL) {
longest_found_length = substring_length;
}
}
}
free(candidate_substring);
return longest_found_length;
}
一些不同的優化,你可以這樣做:
// if this can't be longer, then don't bother checking it. You can play games with the for loop to not have this happen, but it's more complicated.
if (substring_length <= longest_found_index) {
continue;
}
和
// there are more optimizations you could do to this, but don't check
// the substring if it's longer than b, since b can't contain it.
if (substring_length > length_b) {
continue;
}
和
if (strstr(B, candidate_substring) != NULL) {
longest_found_length = end_position - start_position + 1;
} else {
// if nothing contains the shorter string, then nothing can contain the longer one, so skip checking longer strings with the same starting character
break; // skip out of inner loop to next iteration of start_position
}
而是每個候選子複製到一個新的字符串的,你可以與t進行角色互換他end_position + 1
和NUL
字符。然後,在b中查找該子字符串後,將原始字符替換爲end_position+1
。這會更快,但稍微複雜一些。
真的不喜歡你如何做'Y = X;' - 這是一個內存泄漏,並有可能發生緩衝區溢出。 – paddy
從valgrind中顯示第一對錯誤是明智的;我們不應該猜測它正在報告什麼。 –
請使用真實的變量名稱。 ''a'len'代表'm','b_len'代表n,'longestSoFar'代表'X'(如果這是準確的)等等。 – djechlin