Skip to content

Commit 486ec6d

Browse files
author
Stephen Brennan
committed
Fixed prominent bug in lsh_split_line. Also, switched to not copying the strings from strtok().
1 parent 9f2b98a commit 486ec6d

File tree

1 file changed

+7
-25
lines changed

1 file changed

+7
-25
lines changed

src/main.c

Lines changed: 7 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -192,22 +192,18 @@ char *lsh_read_line(void)
192192
*/
193193
char **lsh_split_line(char *line)
194194
{
195-
int bufsize = LSH_TOK_BUFSIZE, position = 0, toklen;
196-
char **tokens = malloc(bufsize * sizeof(char));
197-
char *token, *token_copy;
195+
int bufsize = LSH_TOK_BUFSIZE, position = 0;
196+
char **tokens = malloc(bufsize * sizeof(char*));
197+
char *token;
198198

199199
token = strtok(line, LSH_TOK_DELIM);
200200
while (token != NULL) {
201-
toklen = strlen(token);
202-
token_copy = malloc((toklen + 1) * sizeof(char));
203-
strcpy(token_copy, token);
204-
205-
tokens[position] = token_copy;
201+
tokens[position] = token;
206202
position++;
207203

208-
if (position <= bufsize) {
204+
if (position >= bufsize) {
209205
bufsize += LSH_TOK_BUFSIZE;
210-
tokens = realloc(tokens, bufsize);
206+
tokens = realloc(tokens, bufsize * sizeof(char*));
211207
if (!tokens) {
212208
fprintf(stderr, "lsh: allocation error\n");
213209
exit(EXIT_FAILURE);
@@ -220,20 +216,6 @@ char **lsh_split_line(char *line)
220216
return tokens;
221217
}
222218

223-
/**
224-
@brief Free null-terminated array of strings.
225-
@param args List to free.
226-
*/
227-
void lsh_free_args(char **args)
228-
{
229-
char **iter = args;
230-
while (*iter != NULL) {
231-
free(*iter);
232-
iter++;
233-
}
234-
free(args);
235-
}
236-
237219
/**
238220
@brief Loop getting input and executing it.
239221
*/
@@ -250,7 +232,7 @@ void lsh_loop(void)
250232
status = lsh_execute(args);
251233

252234
free(line);
253-
lsh_free_args(args);
235+
free(args);
254236
} while (status);
255237
}
256238

0 commit comments

Comments
 (0)