I am reading in a line of text from a file, and trying to split it on spaces with strtok()
, then storing each token in an array of char pointers using strcpy()
, within a function called tokenize
.
Code:
/**
** Tokenizes contents of buffer into words
** Delimiter is a space character
*/
void tokenize(char *buffer, char *tokens[]){
char *token = NULL;
int i = 0;
token = strtok(buffer, " ");
while(token != NULL){
strcpy(tokens[i], token);//seg fault line
token = strtok(NULL, " ");
i++;
}
}
I assumed, based on the function description in K&R, that my call would work because I passed a char pointer, which is what tokens[i]
should dereference to, and a another char pointer containing the memory address of the string to be copied, which is what token
should be. However, I get a seg fault when I try to strcpy
.
This function is called in main
immediately after a line is retrieved using a call to fgets()
. buffer
is declared as char buffer[MAXLINE_LEN - 1]
which gives it a size of 100. tokens
is declared as char *tokens[MAXLINE_LEN - 1]
.
Call to tokenize
in main
:
while(fgets(buffer, MAXLINE_LEN, inputFile)){
int choice;
printf("%s", buffer);
tokenize(buffer, tokens);
/**
....
*/
}
I am using: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
EDIT:
Declaration of tokens
(this occurs before the while-loop shown above, and in main
):
char *tokens[MAXLINE_LEN - 1];//MAXLINE_LEN - 1 = 100
int a;
for(a = 0; a < MAXLINE_LEN - 1; a++)
tokens[a] = NULL;