-1

I am trying to get work this piece of code from Kernighan's book The practice of programming on my workstation(windows 7 + vs2015 community edition)

I get a strange error.

void generate(int nwords) {
    State *sp;
    Suffix *suf;

    char *prefix[NPREF];
    char *w = NULL;

    int i, nmatch;

    for (i = 0; i < NPREF; i++)
        prefix[i] = NONWORD;

    for (i = 0; i < nwords; i++) {
        sp = lookup(prefix, 0);
        nmatch = 0;

        for (suf = sp->suf; suf != NULL; suf = suf->next) {
            if (rand() % ++nmatch == 0) {
                w = suf->word;
            }
            if (nmatch == 0)
                printf("internal error: no suffix %d %s", i, prefix[0]);
            if (strcmp(w, NONWORD) == 0)
                break;

            printf("%s ", w);

            memmove(prefix, prefix + 1, (NPREF - 1) * sizeof(prefix[0]));

            prefix[NPREF - 1] = w;
        }   
    }
}

for (suf = sp->suf; suf != NULL; suf = suf->next)

Unhandled exception at 0x000000013F5C1564 in CompareCandCsharp.exe: 0xC0000005: Access violation reading location 0x0000000000000010.

My implementation is similar to described here - Working with arrays and reading text files

Seems algorithm works - but on my computer it fails. I can't find mindfull porpose for this. Could you please give your suggestions.

Community
  • 1
  • 1
  • 1
    How do you know `lookup()` returns a non-NULL pointer? – Sourav Ghosh Jul 15 '16 at 07:59
  • 1
    Are you sure that `lookup` returns a non-null pointer? If you run in a debugger and let it catch the crash (which you should always do btw) what is the value of `sp`? Are you *sure* the crash is at that `for` loop statement? – Some programmer dude Jul 15 '16 at 08:00
  • I am not so cool in c (and c on windows is under my mind)=( my basic language is c#. Of course it can return null pointer but basic script implementation doesn't do anything for checking it. Yes I am sure because debugger stay right there after the error. Maybe I would checking it on linux =( – Роман Иванов Jul 15 '16 at 08:07
  • 1
    If a function you call can return a null pointer, you must always check for that before dereferencing the pointer. Dereferencing a null pointer is bad, as you noticed. – Some programmer dude Jul 15 '16 at 08:15
  • I think your notice is usefull and chek it of course =) But seems problem lays deeper because i get this error when I get in main array prefix[NPREF] two identical words from text. – Роман Иванов Jul 15 '16 at 08:18

1 Answers1

0

After several hours of debugging I have found a small mistake in expected method.

  for (suf = sp->suf; suf != NULL; suf = suf->next) {
        if (rand() % ++nmatch == 0) {
            w = suf->word;
        }

There is no bracket after if in this line so all other code in method try set w many times and of course it leads to memory errors =). Thanx for minusing my question before reading it =))