A small question about using strtok

Source: Internet
Author: User
Tags strtok

Today, when I got a little program, I reported an error and encountered a problem. Let's look at the code first.

int main(int argc, char* argv[]){        char *filename = "interface_ipset_1_1.json";char* split1 = "_";char* split2 = ".";char  splitfile1[4][NAME_MAX];        sagent_string_split(filename,split1,splitfile1,4);printf("1 = %s.",splitfile1[0]);        reuturn 0;}
int32_t sagent_string_split(char * str, const char * split,        char split_str[][NAME_MAX], int32_t max_num){    if (st== NULL || split == NULL || split_str == NULL || max_num <= 0)    {        printf("sagent_string_split params have error!\n");    }char* result = NULL;char* endstr = NULL;    result = strtok_r(str, split,&endstr);    int32_t i = 0;    while (result )        {        if (i >= max_num)        {            printf("split num is more than max_num = %d.", max_num);            return -1;        }        printf("i = %d,result = %s",i,result);        strncpy(split_str[i++], result, NAME_MAX - 1);        result = strtok(NULL, split);      }    return 0;}int main(int argc, char* argv[]){        char *filename = "interface_ipset_1_1.json";char* split1 = "_";char* split2 = ".";char  splitfile1[4][NAME_MAX];        sagent_string_split(filename,split1,splitfile1,4);printf("1 = %s.",splitfile1[0]);    reuturn 0;}


When executing this program, an error is reported, such as segmentation fault. Where should I step on the memory. The original char * filename = "interface_ipset_1_1.json"; this declaration is a constant and cannot be changed. strtok will modify it during use, resulting in an error. So pay attention to it. You can declare char filename [64] = "interface_ipset_00001.json"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.