2016-08-02 50 views
-2

我試過了一個簡單的程序在我的Linux機器上使用分隔符(「,」)標記字符串並打印所有的標記值。但它試圖打印令牌值的第一個語句崩潰。打印令牌從strtok或strtok_r返回崩潰

這裏是我的程序

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

回答

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()將與可寫存儲器應付。

+0

呃..謝謝serhio :) – Harish