Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions src/core/parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,34 @@ ParsedCommand *parse_command(char *input) {
char *input_copy = strdup(input);
if (!input_copy) return NULL;

char *original_input_copy = input_copy;
input_copy = trim_whitespace(input_copy);
if (strlen(input_copy) == 0) {
PARSER_DEBUG("Empty command after trimming");
free(input_copy);
free(original_input_copy);
original_input_copy = NULL;
return NULL;
}

ParsedCommand *cmd = calloc(1, sizeof(ParsedCommand));
if (!cmd) {
PARSER_DEBUG("Failed to allocate ParsedCommand");
free(input_copy);
free(original_input_copy);
original_input_copy = NULL;
return NULL;
}

// Use calloc to ensure all entries are initialized to NULL
cmd->args = calloc(MAX_ARGS, sizeof(char *));
if (!cmd->args) {
PARSER_DEBUG("Failed to allocate args array");
free(input_copy);
free(original_input_copy);
original_input_copy = NULL;
free(cmd);
return NULL;
}

int arg_count = 0;
char *token, *saveptr = NULL;

// Tokenize and process input
token = strtok_r(input_copy, " \t", &saveptr);
while (token != NULL && arg_count < MAX_ARGS - 1) {
Expand Down Expand Up @@ -81,13 +83,17 @@ ParsedCommand *parse_command(char *input) {
// Get next token
token = strtok_r(NULL, " \t", &saveptr);
}

// Ensure NULL termination
cmd->args[arg_count] = NULL;

PARSER_DEBUG("Command parsed with %d arguments", arg_count);

free(input_copy);

if(original_input_copy){
free(original_input_copy);
original_input_copy = NULL;
}


return cmd;
}

Expand All @@ -103,4 +109,4 @@ void free_parsed_command(ParsedCommand *cmd) {
free(cmd->input_file);
free(cmd->output_file);
free(cmd);
}
}