Reputation: 109
I am trying to implement function to split strings, but i keep getting segmentation faults. I am working on Windows XP, and therefore i also had to implement strdup(), because Windows API doesn't provide it. Can anyone tell me what's wrong with the following piece of code.
char** strspl(char* str, char* del)
{
int size = 1;
for(int i = 0; i < strlen(str);) {
if(strncmp(str + i, del, strlen(del)) == 0) {
size++;
i += strlen(del);
}
else {
i++;
}
}
char** res = (char**)malloc(size * sizeof(char*));
res[0] = strdup(strtok(str, del));
for(int i = 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 a debugger i found out, that program crashes after following line:
res[0] = strdup(strtok(str,del));
Also, i fixed strdup(), but there is still no progress.
Upvotes: 1
Views: 2552
Reputation: 244
There are many things wrong with this code, but the main flaw is trying to implement this function. It will only provide you with marginal benefit, if any.
Compare the following two code snippets:
/* Using strtok... */
char *tok = strtok(str, del);
while (tok != NULL) {
/* Do something with tok. */
tok = strtok(NULL, del);
}
-
/* Using your function... */
char **res = strspl(str, del, &size);
size_t i;
for (i = 0; i < size; i++) {
/* Do something with *(res + i). */
}
Upvotes: 0
Reputation: 2967
malloc
does not initialize the allocated memory to \0
. Have you tried using calloc
instead? I suspect the seg faults are due to the res[i] != NULL
comparison.
Upvotes: 0
Reputation: 108986
You're not counting the null terminator and you are copying the wrong number of bytes
char* strdup(char* str) {
char* res = (char*)malloc(strlen(str)); /* what about the null terminator? */
strncpy(res, str, sizeof(str)); /* sizeof(str)
** is the same as
** sizeof (char*) */
return res;
}
Upvotes: 1
Reputation: 994619
Your strdup()
function is not correct. The sizeof(str)
in there is the size of the str
pointer (probably 4 or 8 bytes), not the length of the string. Use the library provided _strdup()
instead.
Upvotes: 0