Reputation: 3
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.
Upvotes: 0
Views: 1780
Reputation: 85361
I see 2 issues with the code:
The first call to strtok
can return NULL
. If that happens, you should not call strtok
again.
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);
}
Upvotes: 2