简体   繁体   中英

segmentation fault double pointer

I'm having a segmentation fault on the following code and i really don't see what i missed, the aim of this code is to retrieve lines of a .csv and put them in a 2D array created with a double pointer.

The seg fault is situated at the last assigment of plaintexts[i][j] for the 1st line of the csv file.

Your help would be much appreciated (on this problem since yesterday...)

int main(){


int n=48; //nbers of columns in csv file
int m=60; //nbers of lines in csv file


int cpt,i,j;
cpt=0;
i=0;
FILE *fp;
char *token;
const char s[2] = ",";

unsigned char **plaintexts;
plaintexts = malloc(sizeof(*plaintexts) * m);

char *str=malloc(sizeof(char)*15*n); //maximum 15 char per box
fp = fopen("aes_traces.csv","r");




while(fgets(str,15*n,fp)!=NULL){

    plaintexts[i] = malloc(sizeof(*plaintexts[i]) * n);
    token = strtok(str,s);
    j=0;
    while(token != NULL){
        printf("%s\n", token);
        token = strtok(NULL,s);
        plaintexts[i][j]=(unsigned char) (*token);

        j++;

    }

    i++;
    free(str);
    free(token);
}


fclose(fp);

}
while(token != NULL){
    printf("%s\n", token);
    token = strtok(NULL,s); // A
    plaintexts[i][j]=(unsigned char) (*token); // B

    j++;
}

If this loop runs at least once, it will end in a segfault. Why? The loop can't terminate until token is set to NULL in the line I marked A and then dereferenced in the line I marked B . Dereferencing a NULL will cause a segfault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM