Reputation: 13
#define delims "\t"
char **parser(char *line)
{
int position = 0;
char **tokens = malloc(64* sizeof(char*));
char *token;
token = strtok(line, delims);
while (token != NULL) {
tokens[position] = token;
position++;
token = strtok(NULL, delims);
}
tokens[position] = NULL;
return tokens;
}
int main(){
char **args;
char *line="abc\tabc";
args=parser(line);
}
When i try to run this code, i am getting "Segmentation fault (core dumped)" error. I tried this on linux with gcc. Problem is not about tokens' size.
Upvotes: 0
Views: 598
Reputation: 33932
In
char *line="abc\tabc";
"abc\tabc"
is a string literal, a const char[8]
and that const
is extremely important. Writing to const
data invokes undefined behaviour because it should not be changed. Often this is accidentally enforced by storing it in non-writable storage.
strtok
is a destructive function. It is going to try to insert null characters between each token and it cannot do this if the string is in non-writable storage.
Allocate some non-constant storage
char line[] = "abc\tabc";
Upvotes: 2
Reputation: 223972
The strtok
function modifies the string it tokenizes. You're passing in a pointer to a string literal, and string literals are read only. Attempting to modify them invokes undefined behavior which in this case causes a crash.
Change line
to an array so that it can be modified.
char line[]="abc\tabc";
Upvotes: 3