Skip to content

Commit c8b2d3a

Browse files
committed
Add memory management for command structure
1 parent f9c6c82 commit c8b2d3a

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

src/parser.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,31 @@ int parse_command_line(const char *cmdline, command_t **cmd, int *bg) {
136136
return 0;
137137
}
138138

139+
void free_command(command_t *cmd) {
140+
if (!cmd) {
141+
return;
142+
}
143+
144+
for (int i = 0; i < cmd->argc; i++) {
145+
free(cmd->argv[i]);
146+
}
147+
148+
if (cmd->infile) {
149+
free(cmd->infile);
150+
}
151+
if (cmd->outfile) {
152+
free(cmd->outfile);
153+
}
154+
155+
command_t *next = cmd->next;
156+
157+
free(cmd);
158+
159+
if (next) {
160+
free_command(next);
161+
}
162+
}
163+
139164
/*
140165
* get_next_token - Retrieve the next token from the input string.
141166
*

src/shell.c

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ void shell_loop(int emit_prompt) {
4040

4141
void eval(const char *cmdline) {
4242
command_t *cmd = NULL;
43-
4443
int bg = 0;
4544

4645
/* Parse the command line into a command_t structure */
@@ -50,12 +49,18 @@ void eval(const char *cmdline) {
5049
}
5150

5251
/* If no command was entered, return */
53-
if (cmd == NULL || cmd->argv[0] == NULL)
52+
if (cmd == NULL || cmd->argv[0] == NULL) {
53+
if (cmd) {
54+
free_command(cmd);
55+
}
5456
return;
57+
}
5558

5659
/* Execute built-in commands if applicable */
57-
if (builtin_cmd(cmd))
60+
if (builtin_cmd(cmd)) {
61+
free_command(cmd);
5862
return;
63+
}
5964

6065
/* Execute external command(s), including handling of:
6166
- Process creation with proper process group management
@@ -66,8 +71,8 @@ void eval(const char *cmdline) {
6671
TODO: Implement execution of external commands.
6772
*/
6873

69-
/* Free any allocated memory for the command structure, if needed */
70-
/* TODO: Free command_t structure resources if dynamically allocated */
74+
/* Free any allocated memory for the command structure */
75+
free_command(cmd);
7176
}
7277

7378
void eval_script(const char *filename) {

0 commit comments

Comments
 (0)