Exception: 'Access violation reading location'

0

Trying to read all words from a string with a strtok(), but it returns an exception when it reaches the end and I just can't figure out why. Sorry if duplicate.

strcpy(now, strtok(text, del));
do {
    if (palindrome(now))
        add_list(now);
    p = strtok(NULL, del);
    strcpy(now,p);
} while (p);

I get this:

Exception thrown at 0x7C07EE43 (ucrtbased.dll) in strings.exe: 0xC0000005: Access violation reading location 0x00000000.

c++
exception
char
strtok
asked on Stack Overflow Oct 26, 2019 by wyrd17 • edited Oct 27, 2019 by ZF007

1 Answer

2

I see 2 issues with the code:

  1. The first call to strtok can return NULL. If that happens, you should not call strtok again.

  2. The second call to strtok can return NULL. In that case strcpy(now,p); will crash, since it's arguments may not be NULL.

Change the code to something like this (untested):

p = strtok(text, del);
while (p) {
    strcpy(now, p);
    if (palindrome(now))
        add_list(now);
    p = strtok(NULL, del);
}
answered on Stack Overflow Oct 26, 2019 by rustyx

User contributions licensed under CC BY-SA 3.0