0

I tested a piece of code to figure out what's causing the segmentation fault with the 'load' function. The code below opens the large dictionary. Then it scans and prints each string inside the dictionary. My problem is that this code is causing a segmentation fault:

int main(int argc, char* argv[])
{
    FILE *file = fopen(argv[1], "r");

    if (file == NULL)
    {
        return 1;
    }

    char buffer[27];

    while (fscanf(file, "%s", buffer) != EOF)
    {
        printf("%s\n", buffer);
    }

}

However, if I replace char buffer[27]; with `char *buffer = malloc(sizeof(char)*27);' (and call free at the end), the code works fine. Shouldn't it work fine with the array too? What am I missing here?

Thanks in advance

1 Answer 1

0

That's the thing about memory violations: unpredictable results. Any word longer than 26 characters will violate memory regardless of how buffer is defined. What does the spec say about length of words in the large dictionary? (perhaps search the spec for mention of the constant LENGTH). When run with the large dictionary, the char * version should produce valgrind errors even if it doesn't segfault.

1
  • Ok, I get it now. the max length of word in the large dictionary is 45 as given by the constant LENGTH but I was using 26. My bad.
    – Soumik
    Mar 22 at 8:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .