'Getting Segmentation Fault error with strtok and fopen

Can anybody pls tell me why am I getting segmentation fault (core dumped) for this piece of code?

//Reading from the card.txt file
char *cards[54];
char *child_cards[54];
for(i=0; i<54; i++){
    cards[i] = malloc(100);
    child_cards[i] = malloc(100);
}

char buff[BUFSIZE];
char *p = NULL;
FILE *fp;
fp = fopen(argv[3], "r"); 

while(fgets(buff, 999, fp) != NULL) 
{
    p = strtok (buff," ");
    while (p != NULL)
    {
        strcpy(cards[total_card], p);
        p = strtok (NULL, " ");           
        total_card += 1;
    }
}
fclose(fp);
c


Solution 1:[1]

Your code has a few memory leaks.

For one, what is the BUFSIZE? I ask because you are using fgets(buff, 999, fp) which means the buffer size of that loop would be 999, possibly going over the BUFSIZE.

For two, it's best practice to specify a type when using malloc()

Goes as follows:

malloc(sizeof(char)*100);

Since malloc works in bytes, you would need the size of each character, times the amount of characters you want to use

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1