In this assignment, I'm supposed to split a string using strtok
. (The assignment consists of the comment and the function definition; I fill in the function body.)
It works as far as I've tested. But it seems a little ugly to me. Perhaps it's my Java background, but somehow this just doesn't feel right. Specific concerns:
- Is this easily readable to a more experienced C programmer?
- Can this be made more idiomatic somewhere?
- Is it feasible to split this into several functions? Where would you split it?
- Any corner cases where it might break? Does it leak memory?
/* Parses a string into tokens (command line parameters) separated by space.
* Builds a dynamically allocated array of strings. Pointer to the array is
* stored in variable pointed by argv.
*
* Parameters:
* argv: pointer to the variable that will store the string array
* input: the string to be parsed (the original string can be modified, if needed)
*
* Returns:
* number of space-separated tokens in the string */
int parse_cmdline(char ***argv, char *input)
{
char *token;
int len, num;
len = 4;
*argv = malloc(len * sizeof(char *));
if (*argv == NULL) {
return 0;
}
for (num = 0;; num++, input = NULL) {
token = strtok(input, " ");
if (token == NULL) {
break;
}
if (num >= len) {
char **temp;
len *= 2;
temp = realloc(*argv, len * sizeof(char *));
if (temp == NULL) {
for (int i = 0; i < num; i++) {
free((*argv)[i]);
}
free(*argv);
*argv = NULL;
return 0;
}
*argv = temp;
}
(*argv)[num] = strdup(token);
if ((*argv)[num] == NULL) {
for (int i = 0; i < num; i++) {
free((*argv)[i]);
}
free(*argv);
*argv = NULL;
return 0;
}
}
return num;
}