c - 我在这里遇到段错误

标签 c regex segmentation-fault

#include <stdio.h>
#include <unistd.h>
#include <regex.h>

#define MAX_LINE 80
int position = 0;
int main(void)
{
char *args[MAX_LINE/2+1];
char *tokens[MAX_LINE/2+1];
char *previoustokens[MAX_LINE/2+1];
char *history[10][MAX_LINE];
int should_run = 1;
char *split;
int i = 0;

while(should_run)
{

    tokens[0]=NULL;
    tokens[1]=NULL;

    char* command, param;
    int concurrent = 0;
    printf("osh>");
    fflush(stdout);
    fgets(args, sizeof(args),stdin);

    strtok(args,"\n");
    split = strtok(args," ");
    while(split!=NULL)
    {

        tokens[i]=strdup(split);
        split = strtok(NULL, " ");
        i++;

    }
    regex_t regex;
    int reti;
    char msgbuf[100];

    /* Compile regular expression */
    reti = regcomp(&regex, "^![[:digit:][:digit:]*]", 0);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        exit(1);
    }

    /* Execute regular expression */
    reti = regexec(&regex, args, 0, NULL, 0);
    if (!reti) {
        puts(tokens[0]);
        char *t = tokens[0];
        t++;
        int x;
        for(x=0;x<MAX_LINE/2+1;x++)
        {
            tokens[x]=history[(int)t-1][x];
        }
    }
    regfree(&regex);
}
}

所以这段代码应该做的是获取输入并将其拆分为 token ,然后使用正则表达式检查是否存在与模式匹配的内容,如果是的话,它应该从历史记录中复制一个条目并将其所有内容放入 token ,这就是我收到段错误的地方。

tokens[x] = history[(int)t-1][x];

我不知道为什么这不起作用。 非常感谢您的帮助。

谢谢

最佳答案

编译后阅读您的警告,它们的存在是有原因的。所以, t 是一个 char* 并且您试图将 char*(在我的系统上为 8 个字节)转换为 int(在我的系统上为 4 个字节),您认为会怎样?段错误是由该行引起的,因为 (int)t-1 可能非常大( t 是一个 char* 并且它存储一个地址),因此您试图访问未分配的内存

关于c - 我在这里遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996325/

相关文章:

c - 从没有 '\n' 的输入文件打印行的最佳方法?

无法在调试器中重现错误

c++ - 行号 : Any way to use __LINE__ to return line number of input file?

regex - 使用 RegEX 在 Notepad++ 中添加前缀和附加

android - 谷歌地图 Activity 因后退按钮上的 SIGSEGV 而崩溃

java - 迭代 vector 分配时出现 Matlab 段错误

C——指向指针数组的指针

创建具有特定顺序的旋转表?

python - 如何删除Python中两个特定单词之间的文本

java - 根据正则表达式分割字符串