【问题标题】:Segmentation fault appearing, when using fgets a second time第二次使用 fgets 时出现分段错误
【发布时间】: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 任何东西。

【问题讨论】:

标签: c string segmentation-fault fgets


【解决方案1】:

你程序中的崩溃来自这一行:

sentence = strtok_r(inputString,Limits,cont);

要超越它,您必须将cont 声明为char * 并将其地址传递给strtok_r

sentence = strtok_r(inputString, Limits, &cont);

为了避免死循环,在while 语句中的strtok_t 中,您必须按照strtok_r 手册页中指定的方式将inputString 更改为NULL

在第一次调用 strtok_r() 时,str 应该指向要被 已解析,并且 saveptr 的值被忽略。在随后的调用中,str 应该是 NULL,并且 saveptr 应该是 自上次调用以来没有变化。

所以对strtok_r 的第二次调用应该如下所示:

sentence = strtok_r(NULL, Limits, &cont);

另一个注意事项是关于处理fgets 错误情况,这不能仅由分号; 构成,您可以按照类似的方式进行:

if (fgets(inputString, 255, stdin) != NULL) {
    fprintf(stderr, "Error while reading input text\n.");
    exit(EXIT_FAILURE);
}

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    相关资源
    最近更新 更多