I have this simple line parser into tokens function... But something im missing.
int parse_line(char *line,char **words){
int wordc=0;
/* get the first token */
char *word = strtok(line, " ");
words[wordc]=(char*)malloc(256*sizeof(char));
strcpy(words[wordc++],word );
/* walk through other tokens */
while( word != NULL ) {
word = strtok(NULL, " ");
words[wordc]=(char*)malloc(256*sizeof(char));
strcpy(words[wordc++],word );
}
return wordc;
}
When i run it i get a segmentation fault! I give as first argument char[256] line and as second of course a char** words but i have first malloc memory for that one. like that
char **words = (char **)malloc(256 * sizeof(char *));
main:
.
.
.
char buffer[256];
char **words = (char **)malloc(256 * sizeof(char *));
.
.
.
n = read(stdin, buffer, 255);
if (n < 0){
perror("ERROR");
break;
}
parse_line(buffer,words);
When program executes parse_line it exits with segmentation fault
Found where the seg fault occures. And it's on that line here:
strcpy(words[wordc++],word );
And specifically on the first strcpy. Before it even reaches the while loop
main()in which you define an example line and you call theparse_line()function - Roberto Caboni