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"