[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
SegFault with Bison Grammar
From: |
Kyle Brandt |
Subject: |
SegFault with Bison Grammar |
Date: |
Fri, 18 Sep 2009 11:50:33 -0400 |
I'm not quite sure how memory allocation is working with Bison, but with the
following Grammar, my code segfaults when my execute_command function is
called from the redirect rule with an argument more than 5 char in length,
but it works fine when called from command rule. Anyone see what I am doing
wrong?
Thank you,
Kyle
//Some Bison Grammar
redirect:
external_cmd GT WORD {
printf("Redirecting stdout of %s to %s\n", $1->cmd, $3);
printf("DEBUG: GT\n");
execute_command($1, 0);
}
;
command:
builtin_cmd |
redirect |
external_cmd {
execute_command($1, 0);
}
;
builtin_cmd:
variable_assignment |
print_var_command |
help_command |
chdir_command |
pwd_command |
exit_command
;
external_cmd:
WORD arg_list {
//execute_command($1, $2);
//printf("Shouldn't be here if no arguments\n");
$$ = malloc( sizeof(struct ext_cmd) );
if ( $$ == NULL)
printf("Memory Allocation Error\n");
$$->cmd = $1;
$$->args_pp = &($2);
} |
WORD {
$$ = malloc( sizeof(struct ext_cmd) );
if ( $$ == NULL)
printf("Memory Allocation Error\n");
$$->cmd = $<string>1;
$$->args_pp = NULL;
}
;
arg_list:
WORD arg_list {
$$ = malloc( sizeof(struct node));
$$->next = $2;
$$->val = $<string>1;
} |
WORD {
$$ = malloc( sizeof(struct node));
$$->next = NULL;
$$->val = $<string>1; }
;
//Relevant Struct
struct node {
char * val;
struct node * next;
};
struct ext_cmd {
char * cmd;
struct node ** args_pp;
};
//Function that segaults:
void execute_command(struct ext_cmd * cmd, int redirection) {
char * arguments[_POSIX_ARG_MAX];
struct node ** node_pp = cmd->args_pp;
int num_args = 1;
pid_t pid;
int status;
arguments[0] = cmd->cmd;
printf("DEBUG: Command to run is %s\n", cmd->cmd);
if (node_pp != NULL) {
while ( *node_pp != NULL ) {
//printf("DEBUG: Adding Argument %s\n", (*node_pp)->val);
num_args += 1;
arguments[num_args - 1] = (*node_pp)->val;
node_pp = &(*node_pp)->next;
}
}
arguments[num_args] = NULL;
if ( (pid = fork()) < 0 ) {
printf("Error on fork\n");
} else if ( pid == 0 ) {
if (execvp(arguments[0], arguments) == -1) {
printf("\nError, unable to execute command %s\n", arguments[0]);
exit(1);
}
}
if ( (pid = waitpid(pid, &status, 0)) < 0)
printf("Wait Error\n");
}
//Only segfaults
kbsh:/home% ls / > foo
Redirecting stdout of ls to foo
DEBUG: GT
DEBUG: Command to run is ls
Here
Here2
Error, unable to execute command ls
kbsh:/home% ls /home
DEBUG: Command to run is ls
Here
Here2
kbrandt auser
kbsh:/home% ls /home > foo
Redirecting stdout of ls to foo
DEBUG: GT
DEBUG: Command to run is ls
Here
zsh: segmentation fault ./cd_shell
- SegFault with Bison Grammar,
Kyle Brandt <=