“Works on my machine”, will not work as a leetcode submission due to potential heap buffer overflow. I tried a similar loop outside of the line 7 while loop and it causes no problems. I know there is probably a solution including strstr() but I want to make this implementation work if possible. Leetcode says the problem lies on line 10, please help me alter the code to make it submissable, but also help me understand why this was problematic in the first place if possible. (Question 1071)
char* gcdOfStrings(char* str1, char* str2)
{
char* jim = (char*)malloc(1001 * sizeof(char));
char* hen = (char*)malloc(1001 * sizeof(char));
int longest = strlen(str1) > strlen(str2) ? strlen(str1) : strlen(str2);
int i=0, counter=0;
while(str1[i] && str2[i])
if(str1[i] == str2[i]){
jim[i] = str1[i];
while(strlen(hen)+ strlen(jim) < longest){
strcat(hen, jim);
if(strcmp(jim, str1) == 0) counter++;
if(strcmp(jim, str2) == 0) counter++;
}
memset(hen,0,strlen(hen));
i++;
}else
break;
jim[i]='';
return counter == 2 ? jim : "";
}
Ran it locally and it worked as intended, apparently it poses some issues that I cannot see.
10397423 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.