Noticed this after making the post here:
Code:
char**result = malloc(sizeof(char));
And was even more surprised that code was working... What exactly was happening?
So, I have this, let the point where reallocating memory with each token found has not been done yet.
Code:
static char** splitstring(char *str, int *noOfTokens)
{
char **result = malloc(sizeof(char*));
char *token = strtok(str, " ");
*noOfTokens = 0;
while (token)
{
if (*noOfTokens)
result = realloc(result, sizeof(char*) * ((*noOfTokens) + 1));
result[*noOfTokens] = malloc(strlen(token) + 1);
strncpy(result[*noOfTokens], token, strlen(token) + 1);
token = strtok(NULL, " ");
(*noOfTokens)++;
}
return result;
}
I'm not sure how the part about reallocating more memory than I need to avoid calling realloc with every run would be done though I am sure I have seen this used before in some code. Any hints?