windows - C split string function -
i trying implement function split strings, keep getting segmentation faults. working on windows xp, , therefore had implement strdup(), because windows api doesn't provide it. can tell me what's wrong following piece of code.
char** strspl(char* str, char* del) { int size = 1; for(int = 0; < strlen(str);) { if(strncmp(str + i, del, strlen(del)) == 0) { size++; += strlen(del); } else { i++; } } char** res = (char**)malloc(size * sizeof(char*)); res[0] = strdup(strtok(str, del)); for(int = 0; res[i] != null; i++) { res[i] = strdup(strtok(null, del)); } return res; } char* strdup(char* str) { char* res = (char*)malloc(strlen(str)); strncpy(res, str, sizeof(str)); return res; }
edit: using debugger found out, program crashes after following line:
res[0] = strdup(strtok(str,del));
also, fixed strdup(), there still no progress.
you're not counting null terminator , copying wrong number of bytes
char* strdup(char* str) { char* res = (char*)malloc(strlen(str)); /* null terminator? */ strncpy(res, str, sizeof(str)); /* sizeof(str) ** same ** sizeof (char*) */ return res; }
Comments
Post a Comment