I have a program with the aim of finding the GCD of two strings s and t, i.e, return the largest x such that x|s and x|t. While testing this program, I encountered a heap-buffer-overflow. I am aware that this error implies a segmentation fault. However, I am not sure where in the program this error arises.
string gcdOfStrings(string str1, string str2) {
const char *ptrI = str1.c_str(), *ptrJ = str2.c_str();
char *str3 = new char[1000 + 1], *ptrK = str3;
bool boolI = false, boolJ = false;
while (*ptrI == *ptrJ) { *ptrK++ = *ptrI++; }
ptrI = str1.c_str();
while ( (*ptrI != '\0') || (*ptrJ != '\0') || (*ptrK != '\0') ) {
if (*ptrK == '\0') { ptrK = str3; }
if (*ptrI != *ptrK) { boolI = true; }
if (*ptrI != '\0') { ptrI++; }
if (*ptrJ != *ptrK) { boolJ = true; }
if (*ptrJ != '\0') { ptrJ++; }
if ( (boolI != true) && (boolJ != true) ) { *ptrK = '\0'; string t(str3); delete[] str3; return t; }
ptrK++;
}
return "";
}
Example 1:
Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB"
Example 3:
Input: str1 = "ABABCB", str2 = "ABAB" Output: ""