I am getting a segmentation error here

#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);
}
}

so what this code is supposed to do is get an input and split it in to tokens and then check with regex if there is a match to the pattern if so it should copy an entry from the history and place all its belongings in tokens and this is where i get the segmentation error.

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

I'm not sure why this is not working. Your help is much appreciated.

Thanks

Answers


Read your warnings after compiling , they are there for a reason. so , t is a char* and you're trying to cast char*(8bytes on my system) to an int(4 bytes on my system) , how do you think that's gonna go ? The segmentation fault is caused by that line because (int)t-1 might be something really big ( t is a char* and it stores an address ) and so you're trying to access unallocated memory


Thanks to Alexie Dariciuc i solved my problem tokens[x]=history[atoi(t)-1][x];

PS: from now on im all over the warnings xD


Need Your Help

Pandas: Spare data, groupby and datetime extension into new dataframe?

datetime pandas indexing

Have been reading a couple of very good posts in here for the last days and unfortunately, I think its my turn right now as I have the following problem:

Interfering Vector in glBegin()

c++ opengl animation

I am trying to implement code for an assignment to render skeleton and mesh animations. In my glBegin(GL_TRIANGLES) section, I have some vectors that appear to be interfering with my information wh...