C segmentation fault using structures -
#include<stdio.h> #include<stdlib.h> #include<string.h> #define max_sub_commands 5 #define max_args 10 struct subcommand { char *line; char *argv[max_args]; }; struct command { struct subcommand sub_commands[max_sub_commands]; int num_sub_commands; }; void readcommand(char *line, struct command **command); void printcommand(struct command **command); void read_args(char *in, char *argv[max_args], int size); void print_args(char *argv[max_args]); int main() { char s[200]; printf("enter command:"); fgets(s,200,stdin); s[strlen(s)-1]='\0'; struct command *command; readcommand(s,&command); printcommand(&command); } void readcommand(char *line, struct command **command) { const char *delim ="|"; const char *k; char *copy; char *l; int i=0; (*command)->num_sub_commands=0; k=strtok(line,delim); while(k!=null) { l=strdup(k); (*command)->sub_commands[i].line=l; printf("(*command)->sub_commands[%d].line=%s,l=%s\n",i,(*command)->sub_commands[i].line,l); i++; printf("%d iteration\n",i); (*command)->num_sub_commands++; printf("%d number of subcommands\n",(*command)->num_sub_commands); k=strtok(null,delim); } (*command)->sub_commands[i].line=null; for(i=0;(*command)->sub_commands[i].line!=null;i++) { copy=strdup((*command)->sub_commands[i].line); read_args(copy,(*command)->sub_commands[i].argv,max_args); } } void read_args(char *in, char *argv[max_args], int size) { const char *del =" "; int i=0; const char *k1; char *l1; k1=strtok(in,del); while(k1!=null) { l1=strdup(k1); argv[i]=l1; //printf("argv[%d]=%s\n",i,argv[i]); i++; //printf("k1=%s\n",k1); //printf("l1=%s\n",l1); k1=strtok(null,del); } argv[i]=null; } void printcommand(struct command **command) { int i; for(i=0;(*command)->sub_commands[i].line!=null;i++) { printf("subcommand[%d]='%s' \n",i,(*command)->sub_commands[i].line); print_args((*command)->sub_commands[i].argv); } } void print_args(char *argv[max_args]) { int i; for(i=0;argv[i]!=null;i++) { printf("argv[%d]='%s' \n",i,argv[i]); } }
i getting segmentation fault, donno why? can help?? getting segmentation fault while runnig in devc++ ide , when running code on shell optimization flag o0 working fine.
i don't see in code malloc (and free).
and in main can do:
struct command command; //i don't understand why using pointers here readcommand(s,command); printcommand(command);
and can change:
void readcommand(char *line, struct command **command); void printcommand(struct command **command);
with:
void readcommand(char *line, struct command *command); void printcommand(struct command *command);
and example printcommand can be:
void printcommand(struct command *command) { int i; for(i=0;command->sub_commands[i].line!=null;i++) { printf("subcommand[%d]='%s' \n",i,command->sub_commands[i].line); print_args(command->sub_commands[i].argv); } }
also remember use free
line
, argv
of subcommand
struct, when finish using them.
Comments
Post a Comment