简体   繁体   中英

Exception: 'Access violation reading location'

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM