Skip to content

Commit

Permalink
Fixed prominent bug in lsh_split_line. Also, switched to not copying …
Browse files Browse the repository at this point in the history
…the strings from strtok().
  • Loading branch information
Stephen Brennan committed Jan 18, 2015
1 parent 9f2b98a commit 486ec6d
Showing 1 changed file with 7 additions and 25 deletions.
32 changes: 7 additions & 25 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -192,22 +192,18 @@ char *lsh_read_line(void)
*/
char **lsh_split_line(char *line)
{
int bufsize = LSH_TOK_BUFSIZE, position = 0, toklen;
char **tokens = malloc(bufsize * sizeof(char));
char *token, *token_copy;
int bufsize = LSH_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;

token = strtok(line, LSH_TOK_DELIM);
while (token != NULL) {
toklen = strlen(token);
token_copy = malloc((toklen + 1) * sizeof(char));
strcpy(token_copy, token);

tokens[position] = token_copy;
tokens[position] = token;
position++;

if (position <= bufsize) {
if (position >= bufsize) {
bufsize += LSH_TOK_BUFSIZE;
tokens = realloc(tokens, bufsize);
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
Expand All @@ -220,20 +216,6 @@ char **lsh_split_line(char *line)
return tokens;
}

/**
@brief Free null-terminated array of strings.
@param args List to free.
*/
void lsh_free_args(char **args)
{
char **iter = args;
while (*iter != NULL) {
free(*iter);
iter++;
}
free(args);
}

/**
@brief Loop getting input and executing it.
*/
Expand All @@ -250,7 +232,7 @@ void lsh_loop(void)
status = lsh_execute(args);

free(line);
lsh_free_args(args);
free(args);
} while (status);
}

Expand Down

0 comments on commit 486ec6d

Please sign in to comment.