今天在弄一下啊小小程序的时候。报错,出现了问题。先看代码

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;
}



在运行这个程序的时候。报错,Segmentation fault 这个错误。哪踩内存了呢。原来char *filename = "interface_ipset_1_1.json"; 这样声明是 一个常量,不可更改的,而strtok在使用过程中会把它进行改动,造成了错误。所以须要注意。

能够这样声明char filename[64] = "interface_ipset_1_1.json"