I'm having problems in figuring out where and why I'm receiving a segmentation fault.
I'm writing a C code that prompts the user to input a regular expression and compile it and then enter a string with multiple sentences:
int main(void){
char RegExp[50];
regex_t CompiledRegExp;
char *para;
char delim[] = ".!?,";
char *sentence;
char *ptr1;
printf("Enter regular expression: ");
fgets(RegExp, 50, stdin);
if (regcomp(&CompiledRegExp,RegExp,REG_EXTENDED|REG_NOSUB) != 0) {
printf("ERROR: Something wrong in the regular expression\n");
exit(EXIT_FAILURE);
}
printf("\nEnter string: ");
strtok_r is used to split the string with either of the following delimiters .,?! and then the resulting token (sentence) is used as the string parameter in the regexec function that searches it to see if the regular expression previously compiled is contained within the token:
if( fgets(para, 1000, stdin)){
char *ptr = para;
sentence = strtok_r(ptr, delim, &ptr1);
while(sentence != NULL){
printf("\n%s", sentence);
if (regexec(&CompiledRegExp,sentence,(size_t)0,NULL,0) == 0) {
printf("\nYes");
} else {
printf("\nNo");
}
ptr = ptr1;
sentence = strtok_r(ptr, delim, &ptr1);
}
}
regfree(&CompiledRegExp);
}
It's probably a silly mistake I'm making but any help in locating the reasons of the segfaul would be greatly appreciated!
EDIT: Moved regfree
to a more suitable location. However, segfault still occurring. I'm pretty sure It has something got to do with either how the regular expression is being read in or how it is being compared in regexec
. Clueless, though.
len = strlen(para); para[len-1] = '\0';
still causes regex to fail – Anthemion