my gcc version is 12.2.0 (Homebrew GCC 12.2.0) While running the code, the terminal reads segmentation fault 11. By using print method and breakpoint method, I narrow the problem down to where it went wrong. However, I couldn't see why.
where it went wrong is down below using annotations to point out.
The code down below is only a part of my whole code, for I delete the unrelated part of the code about the bug to make it easier to read the code.
I am very grateful for those who helps me. btw, English is not my mother tongue. Therefore, if there is any ambiguous or obscure parts in my problem description, plz let me know, I'll provide more explanation and information about the problem I encounter.
void slidingWindow(char *start, char *end){
char charset[2];
charset[0] = *start;
bool overTwo = false;
// the code down below is where it went wrong, but IDK why it's wrong
// segmentation fault 11
while(*end != 0 || strncmp(start,end,1) != 0){
end++;
}
// the above code.
}
int lengthOfLongestSubstringTwoDistinct(char *s){
char *start = s, *end = s;
slidingWindow(start,end);
return 0;
}
int main(){
size_t size = 100001;
char *s = malloc(sizeof(char[size]));
getline(&s,&size,stdin);
lengthOfLongestSubstringTwoDistinct(s);
printf("%d\n", res);
}
segmentation fault 11
char *s = malloc(sizeof(char[size]));
followed bygetline(&s,&size,stdin);
is pretty pointless, you could as well callgetline
straight away. (Althoughgetline
is a dangerous function with lots of quirks and notorious for being a common cause for memory leaks.)while(*end != 0 || strncmp(start,end,1) != 0)
This doesn't make much sense and I suspect you've inverted the logic (check up on De Morgan's laws). The seg fault would be because you keep reading past the null terminator.It would seem that you are rather looking for something like
while((*end != '\0') && (*start == *end))
? That would count up a substring from the beginning of the string until the next non-identical character.