I can't figure out this error.
Problem > Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
char * longestCommonPrefix(char ** strs, int strsSize){
int i = 1;
int j = 0;
int k = 1;
int n = 0;
if (strsSize == 0) return ("");
if (strsSize == 1) return (strs[0]);
if (strsSize > 1 && strcmp(strs[0],"") == 0) return ("");
char *s = calloc(strlen(strs[0]), sizeof(char));
char *temp = calloc(strlen(strs[0]), sizeof(char));
if (!s || !temp) return (0);
// while (strs[0][j] != '\0') {
// temp[j] = strs[0][j];
// j++;
// }
strcpy(temp, strs[0]);
while (k < strsSize) {
j = 0;
n = 0;
memset(s, 0, strlen(s));
while (strs[i][j]){
if (temp[j] == strs[i][j]) {
s[n] = strs[i][j];
n++;
}
else if (temp[j] != strs[i][j]){
break;
}
j++;
}
strcpy(temp, s);
k++;
i++;
}
return (s);
}
It works without any problem on my visual studio but when I submit this code to Leetcode, it always has that error message. I assume error occurs on either line 7 or 8 because it dose not show same error when I hide those two line of codes. Also, when I copy strs[0] string to temp using while loop, it works fine on both Leetcode and visual studio but it does not work when I use "scrcpy" function on Leetcode but again, it works on my visual studio.
Another minor problem. The reason that I use calloc to allocate the memory is because It shows same error message "Address sani~" when using malloc. It does not matter on visual studio. Both calloc and malloc work ok.
I've added an extra memory for NULL terminator.
char *s = malloc((strlen(strs[0]) + 1) * sizeof(char));
It seems alright in my head but It has same memory issue.
I've tried many different ways but I still have issue with the way I use malloc and clear a string.
int len = strlen(strs[0]);
char *temp = malloc((len+1) * sizeof(char))
//it still gives me a memory error.
When I clear my string with memset, it returns a correct output but it does not return the right answer when I clear the string simply using NULL terminator. Is there a difference?
s[j] = '\0';
memset(s, 0, strlen(s));