简体   繁体   中英

Segmentation fault (core dumped) when i trying use strtok in C

#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.

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";

Problem

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.

Solution:

Allocate some non-constant storage

char line[] = "abc\tabc";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM