The problem is to find the longest common prefix in an array of strings ie. [flower, flow, flight]
The code I wrote works when I run it in terminal using gcc but when I try it in Leetcode I get an error? I tried looking it up and I keep getting answers where I'm trying to access memory that isn't there but I don't know where I'm doing that in my code. Can anyone explain it a little better? This is the code:
char* longestCommonPrefix(char** strs, int strsSize) {
char* answer;
answer = malloc(sizeof(char) * strlen(strs[0]) + 1);
strcpy(answer, strs[0]);
for (int i = 0; i < strsSize - 1; i++) {
for (int k = 0; k < strlen(strs[i]) && k < strlen(strs[i + 1]); k++) {
if (strs[i][k] != strs[i + 1][k]) {
answer[k] = '';
break;
}
}
}
printf("%s
", answer);
return answer;
}
Even if I try just this it's still an heap buffer overflow error:
char* longestCommonPrefix(char** strs, int strsSize) {
char* answer = malloc(sizeof(char) * 1000));
return answer;
}
Edit:
I just found a solution on Leetcode someone posted and it creates an array with malloc with no errors.. If anyone call compare this to mine and let me know why malloc works here and not in my function that'd be great.
char * longestCommonPrefix(char ** strs, int strsSize){
char* output = (char*)malloc(sizeof(char));
strcpy(output, "");
if (strsSize == 0) {
return output;
}
int longest = strlen(strs[0]);
for (int i = 1; i < strsSize; i++) {
if (strlen(strs[i]) < longest) {
longest = strlen(strs[i]);
}
for (int j = 0; j < longest; j++) {
if (strs[i][j] != strs[0][j]) {
if (j == 0) {
return output;
} else if (j < longest) {
longest = j;
}
break;
}
}
}
free(output);
output = (char*)malloc((longest + 1) * sizeof(char));
strncpy(output, strs[0], longest);
output[longest] = '';
return output;
}
question from:
https://stackoverflow.com/questions/65661556/c-i-keep-running-into-address-sanitizer-heap-buffer-overflow-in-leetcode 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…