I have a function that is basically a rewritten strtok_r
because that function is causing me grief.
char *betterStrtok(char *str, char *delim, char **loc)
{
int iter = 0;
char *tmp;
if(str)
{
char mod[strlen(str) + 2];
char *out = malloc(strlen(str) + 2);
char curr = str[0];
strcpy(mod, str);
while(curr)
{
tmp = strchr(delim, curr);
if(tmp)
{
mod[iter] = 0;
strcpy(out, mod);
*loc = &mod[iter + 1];
//printf("Inside function: \"%s\"\n", *loc);
return out;
}
if(curr)
{
curr = mod[++iter];
}
else
{
*loc = &mod[0];
strcpy(out, mod);
return out;
}
}
return NULL;
}
else
{
char mod[strlen(*loc) + 2];
strcpy(mod, *loc);
char *tloc = malloc(sizeof loc + 2);
char *out = malloc(strlen(*loc) + 2);
char curr = mod[0];
while(curr)
{
tmp = strchr(delim, curr);
if(tmp)
{
mod[iter] = 0;
strcpy(out, mod);
tloc = &mod[iter + 1];
strcpy(*loc, tloc);
return out;
}
if(curr)
{
curr = mod[++iter];
}
else
{
*loc = &mod[0];
strcpy(out, mod);
return out;
}
}
return NULL;
}
}
So my issue is *loc
has the appropriate thing in it after the first pass, and when I check what's in it outside the function, it's mostly there except the last character is something weird. Let's say this is the setup:
char *addr = malloc(60);
char **supaddr = &addr;
char *strtotok = "Hello, world!";
char *thetok;
thetok = betterStrtok(strtotok, ",", supaddr);
printf("Outside function: \"%s\"\n", addr);
Adding print statements right before the return and right after calling the function shows something like this:
Inside function: " world!"
Outside function: " w"
The question is: how can I prevent the string from changing or how can I do something else so I can save the "rest" of the original string without returning it?