#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(®ex, "^![[:digit:][:digit:]*]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, 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(®ex);
}
}
所以这段代码应该做的是获取输入并将其拆分为 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/