c - Code crashes when splitting the tokens using strtok by passing the string to function -
my code crashes when try split tokens using strtok passing string function. here code:
#define max_string_size 256 #include <stdio.h> #include <string.h> #include <stdlib.h> static void gettokens(char *s1 ,char *ct1 ,char ***pppctoks ,int *ntkns) { char *s2 = null; char *cp = null; cp = strtok(s1, ct1); (*ntkns)++; *pppctoks = (char **) malloc(1 * sizeof(char *)); (*pppctoks)[0] = (char *)malloc(max_string_size * sizeof(char)); (*pppctoks)[0] = cp; while (null != (cp = strtok(null, ct1))) { *pppctoks = (char **)realloc((void *)(*pppctoks), (*ntkns) * sizeof(char *)); (*pppctoks)[(*ntkns)] = (char *)malloc(max_string_size * sizeof(char)); (*pppctoks)[(*ntkns)] = cp; printf("%s\n", (*pppctoks)[(*ntkns)]); (*ntkns)++; } printf("%d", *ntkns); } int main(int argc, char *argv[]) { char ac[max_string_size] = "strtok#should#be tested extent"; int ntkns = 0,inx; char **ppclist = null; gettokens(ac, "#", &ppclist, &ntkns); (inx =0; inx < ntkns; inx++) { printf("%s", ppclist[inx]); //fails in second loop } for(;;); } the first token gets printed. crash occurs while printing further. note using c++ compiler compile c code, don't have 1 c such.
please find working code:
#define max_string_size 256 #include <stdio.h> #include <string.h> #include <stdlib.h> static void gettokens(char *s1 ,char *ct1 ,char ***pppctoks ,int *ntkns) { char *cp = null; /* first token */ cp = strtok(s1, ct1); (*ntkns)++; (*pppctoks) = (char **) malloc(1 * sizeof(char *)); (*pppctoks)[0] = (char *)malloc((strlen(cp) + 1) * sizeof(char)); strcpy((*pppctoks)[0], cp); /* walk through other tokens */ while (null != (cp = strtok(null, ct1))) { (*ntkns)++; (*pppctoks) = (char **)realloc((void *)(*pppctoks), (*ntkns) * sizeof(char *)); (*pppctoks)[*ntkns-1] = (char *)malloc((strlen(cp) + 1) * sizeof(char)); strcpy((*pppctoks)[*ntkns-1], cp); } } int main(int argc, char *argv[]) { char ac[max_string_size] = "strtok#should#be tested extent"; int ntkns = 0,i; char **ppclist = null; gettokens(ac, "#", &ppclist, &ntkns); (i =0; < ntkns; i++) { printf("%s\n", ppclist[i]); } for(;;); } thanks valuable suggestion!!
Comments
Post a Comment