Using Kubuntu 22.04 LTS, Kate v22.04.3, and gcc v11.3.0, I have developed a small program to investigate the use of strtok() for tokenising strings, which is shown below.
#include <stdio.h>
#include <string.h>
int main(void)
{
char inString[] = ""; // string read in from keyboard.
char * token = ""; // A word (token) from the input string.
char delimiters[] = " ,"; // Items that separate words (tokens).
// explain nature of program.
printf("This program reads in a string from the keyboard"
"\nand breaks it into separate words (tokens) which"
"\nare then output one token per line.\n");
printf("\nEnter a string: ");
scanf("%s", inString);
/* get the first token */
token = strtok(inString, delimiters);
/* Walk through other tokens. */
while (token != NULL)
{
printf("%s", token);
printf("\n");
// Get next token.
token = strtok(NULL, delimiters);
}
return 0;
}
From the various web pages that I have viewed, it would seem that I have formatted the strtok() function call correctly. On the first run, the program produces the following output.
$ ./ex6_2
This program reads in a string from the keyboard
and breaks it into separate words (tokens) which
are then output one token per line.
Enter a string: fred , steve , nick
f
ed
On the second run, it produced the following output.
$ ./ex6_2
This program reads in a string from the keyboard
and brakes it into separate words (tokens) which
are then output one token per line.
Enter a string: steve , barney , nick
s
eve
*** stack smashing detected ***: terminated
Aborted (core dumped)
Subsequent runs showed that the program sort of ran, as in the first case above, if the first word/token contained only four characters. However, if the first word/token contained five or more characters then stack smashing occurred.
Given that "char *" is used to access the tokens, why :-
a) is the first token (in each case) split at the second character ?
b) are the subsequent tokens (in each case) not output ?
c) does a first word/token of greater than four characters cause stack smashing?
Stuart