-2

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);
  • 1
    [Please do not post images of code because they are hard to use.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) Code should be posted directly **as text** in your question. – MikeCAT Apr 01 '22 at 13:02
  • 2
    Also don't forget to post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) instead of incomplete code snippet that is not suit for feeding to compilers. – MikeCAT Apr 01 '22 at 13:04
  • Where is the segfault? Is `argv[3]` valid? Is `total_card` initialized? Too much information is missing here. – William Pursell Apr 01 '22 at 13:05
  • 1
    A complete example is one where the code posted doesn't need to be modified before it can be compiled and executed. If you want people to help you, then you have to make it easy for them to help you. – Jeff Holt Apr 01 '22 at 13:08
  • What is `BUFSIZE`? Can `buff` hold enough input from `fgets(buff, 999, fp)`? What is `total_card` What type is it? Where do you initialize it? Without a complete MRE we can only do wild guesses. – Gerhardh Apr 01 '22 at 13:10
  • What arguments do you pass to your program? Does the file exist? You should check return value of `fopen`. What does the file contain? – Gerhardh Apr 01 '22 at 13:13

1 Answers1

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

Primitive
  • 91
  • 1
  • 6
  • There are many people who would dispute your "it's best practice" comment — see [Should I cast the result of `malloc()`?](https://stackoverflow.com/q/605845/15168) I happened to learn C on a system where the cast was imperative (in the days before standard C), so I don't look askance at the cast. – Jonathan Leffler Apr 01 '22 at 14:12
  • @JonathanLeffler I hope my new edit is to your liking – Primitive Apr 01 '22 at 14:16