从strtok或strtok_r崩溃返回的打印令牌

时间:2016-08-02 11:04:09

标签: c segmentation-fault strtok

我在linux机器上尝试了一个简单的程序,它使用分隔符(“,”)对字符串进行标记,并打印所有标记值。但它在第一个试图打印令牌值的声明中崩溃。

这是我的程序

#include <stdio.h>
#include <string.h>

void main()
{
    char *query = "1,2,3,4,5";
    char *token = strtok(query, ",");
    while(token)
    {
        printf("Token: %s \n", token);
        token = strtok(NULL, ",");
    }
}

输出:

Segmentation fault (core dumped)

BT在GDB中:

 (gdb) r
 Starting program: /home/harish/samples/a.out

 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.

构建系统:

64 bit Ubuntu, gcc 4.8.4 version.

1 个答案:

答案 0 :(得分:2)

替换

char *query = "1,2,3,4,5"; /* query is a pointer to literal that may reside in readonly memory */

char query[] = "1,2,3,4,5"; /* query is a writable array initialized with literal data */

所以strtok()将处理可写内存。