strtok() - Segmentation Fault [duplicate]

我的梦境 提交于 2019-12-25 06:38:44

问题


Possible Duplicate:
strtok giving Segmentation Fault

I try to use strtok function to split string in many tokens but in this example it returns me a seg. fault error. Where i'm in wrong??

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

int main(int argc, char** argv){
    int i=0;
    char * string = "HI:HOW:ARE:YOU:?", *tmp;

    while(1){
        if(i==0) tmp=strtok(string,":");
        else tmp=strtok(NULL,":");
        if(tmp==NULL) break;
        printf("%s\n",tmp);
        i++;
    }
    return 1;
}

回答1:


Change

char * string = "HI:HOW:ARE:YOU:?"

for

char string [] = "HI:HOW:ARE:YOU:?"

With char string [] you have an array, and char * you have a pointer. When you declare an array, it will request space to allocate the size of your string. The char * string creates a pointer that points to a literal string.

The problem with char *string it is that the point should not be changed because string literals are typically stored in read-only memory, thus causing undefined behavior 33

( for more detail read this https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals )

Therefore, since with strtok the contents of the string is modified and broken into smaller strings (tokens) you got problems.



来源:https://stackoverflow.com/questions/13208828/strtok-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!