使用strtok时出现段故障

时间:2015-10-09 10:59:11

标签: c

以下是我的代码:

{
  "A": {
    "root": {
      "set": "true",
      "kill": "true",
      "zwrite": "true"
    },
    "abc": {
      "set": "true",
      "kill": "false",
      "zwrite": "true"
    }
  },
  "B": {
    "root": {
      "set": "false",
      "kill": "false",
      "zwrite": "true"
    },
    "abc": {
      "set": "true",
      "kill": "true",
      "zwrite": "true"
    }
  }
}

和json文件' roles.cfg'在代码中使用:

strok

我使用Segmentation fault.分割了一些文字,但执行时出现Reading symbols from ./test2...done. (gdb) b 1 Breakpoint 1 at 0x400b55: file test2.c, line 1. (gdb) r Starting program: /home/insight/test2 Breakpoint 1, main () at test2.c:9 9 char *cmd = "zwr ^A(\"A\")"; (gdb) n 10 int v = checkUserRole(cmd); (gdb) s checkUserRole (cmd=0x4046c4 "zwr ^A(\"A\")") at test2.c:15 15 { (gdb) n 17 u = getenv("USER"); (gdb) n 21 if(strstr(cmd,"(") != NULL){ (gdb) n 22 limiter = "("; (gdb) n 23 token = strtok(cmd,limiter); (gdb) n Program received signal SIGSEGV, Segmentation fault. strtok () at ../sysdeps/x86_64/strtok.S:186 186 ../sysdeps/x86_64/strtok.S: No such file or directory. (gdb) 错误

以下是调试输出:

strtok

我不知道为什么它会在该行出错,我检查所有参数insight@insight-ubuntu64:~$ gcc -g -o test2 test2.c cJSON.c -lm insight@insight-ubuntu64:~$ ,似乎没有问题 //更新:编译时没有警告:

{{1}}

1 个答案:

答案 0 :(得分:5)

strtok修改原始字符串。然后你传递一个你无法修改的字符串文字。您应该像这样声明并初始化cmd -

 char cmd[] = "zwr ^A(\"A\")"; //string: zwr ^A("A")

同样在函数int checkUserRole(char *cmd) -

char fileContent[1000000];   // maybe use a pointer instead and allocate memory on heap