c - Why is one seg faulting and the other not? -
hi have program needs compare string array predefined string when use variable args[0] works in function strcmp below
int gash_execute(char **args){ int i; if(args[0] == null){ return 1; } for(i = 0; < gash_command_num(); i++){ if(strcmp(args[0], functions[i]) == 0){ return(*function_address[i])(args); } } return gash_launch(args); }
however when trying strcmp args[i] such below seg fault. can me find solution problem?
int gash_execute(char **args){ int i; if(args[0] == null){ return 1; } for(i = 0; < gash_command_num(); i++){ if(strcmp(args[i], functions[i]) == 0){ return(*function_address[i])(args); } } return gash_launch(args); }
args[] array of strings separated spaces, program custom shell, pretend in shell command line input "cat echo ls" args[0] "cat" , on. need implement i/o redirection. need check every element of args check if represent symbols "<" ">" "|" , if 1 of them can take there
without seeing code, or report tool such valgrind, can't sure. can tell loop full of potential problems.
for(i = 0; < gash_command_num(); i++){ if(strcmp(args[i], functions[i]) == 0){ return(*function_address[i])(args); } }
it's iterating through 3 arrays (args
, functions
, , function_address
) based on function call takes none of variables (gash_command_num()
) has unknown relation how many elements in arrays.
and it's using 2 global variables (functions
, function_addresses
) contain anything.
if things related, suggest making explicit... suspect they're not. suspect loop logic wrong. it's comparing args[i]
functions[i]
. suspect gash_command_num()
size of functions
, loop walking off args
.
what suspect want see if args[0]
matches function name in functions
, call related function. if args[0]
ls
want check if there's built in shell function ls
, call arguments.
rather searching list on , on again, , having manage 2 parallel lists, better served hash table. keys function names, values function pointers. c doesn't have hash table built in, there's plenty of libraries that. gnome lib solid choice , many other basic functionality c missing.
using hash table, , eliminating globals, code reduces this:
/* encapsulation */ typedef int(*shell_function_t)(char **); int gash_execute(char **args, ghashtable *shell_functions){ int i; if(args[0] == null){ return 1; } shell_function_t func = g_hash_table_lookup(shell_functions, args[0]); if( func ) { return(*func)(args); } else { return gash_launch(args); } }
scanning pipes separate problem. do want loop through args
looking special characters. made simpler if, when create args
, ensure ends null pointer.
for(int = 0; args[i] != null; i++) { ...check if args[i] special... }
Comments
Post a Comment