【发布时间】:2018-05-04 00:35:17
【问题描述】:
这是我的完整代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
#define SEN_LIMITERS ".!?"
int main()
{
char inputexp[256];
char inputString[256];
const char *Limits = SEN_LIMITERS;
char *sentence;
regex_t expression;
char **cont = NULL;
int Words = 0, index;
printf("Please enter the string to analyse: \n");
if(fgets(inputString,255,stdin) != NULL);
printf("Please enter the regular expression :");
if(fgets(inputexp,255,stdin) != NULL);
inputexp[strlen(inputexp)-1] = '\0';
if (regcomp(&expression,inputexp,REG_EXTENDED) != 0) {
printf("ERROR: Something wrong in the regular expression\n");
exit(EXIT_FAILURE);
}
sentence = strtok_r(inputString,Limits,cont);
while(sentence != NULL){
printf("%s\n",sentence);
if (regexec(&expression,sentence,0,NULL,0) == 0) {
printf("Yes ");
} else {
printf("No ");
}
for (index = 0;sentence[index] != '\0';index++)
{
if (sentence[index] == ' ')
Words++;
}
printf("%d words\n",Words);
Words = 0;
sentence = strtok_r(inputString,Limits,cont);
}
return(EXIT_SUCCESS);
}
//停止
由于某种原因,当我运行它时,会在第二个 fgets 之后发生分段错误。
Please enter the string to analyse:
abba and a bee. aah mama mia. there we go again. in the city of miami.
Please enter the regular expression :a[bm].*[ai]
Segmentation fault (core dumped)
我真的不知道为什么会发生这种情况,因为第一个 fgets 似乎正在经历。我不确定我是否应该出于与上述相同的原因而 malloc 任何东西。
【问题讨论】:
-
这个语句应该做什么?
if(fgets(inputexp,255,stdin) != NULL); -
您在某处发生了崩溃。您可能需要对其进行调试。
标签: c string segmentation-fault fgets