Trouble with pointers In C. Segmentation fault -
i'm having trouble project university consists in simulating shell. user types command , program divides line in tokens , checks if 1 of them internal command, such cd, export, jobs , source. prints tokens , basic explanation of command has been found in line. when run on codeblocks works fine, when compile on netbeans in linux, reports several warnings, explain in code , when run message appears: segmentation fault (core dumped). i've been researching , i've found has memory permissions (accessing part of memory not allowed access). can't find way solve it, hope here can me. thanks!
#include <stdio.h> #include <stdlib.h> #define prompt "$" int parse_args(char **args, char *line){ char *token; int n=0; token=strtok(line," "); // warning: assignment makes pointer integer without cast while(token!=null){ printf("token%i: %s\n",n,token); *args=token; n++; *args++; token=strtok(null," ");// warning: assignment makes pointer integer without cast } printf("token%i: %s\n",n,token); *args=token; return n; } char *read_line(char *line){ //expecting argument char* argument of type char** printf("%s ",prompt); *line = malloc(sizeof(500));//warning: assignment makes pointer integer without cast fgets(line,500,stdin); return line; } int execute_line(char *line){//expecting argument char* argument of type char** char**args; parse_args(args,line); check_internal(args); return 0; } int check_internal(char **args){ if( strcmp(*args, "cd")==0 ){ internal_cd(); } else{ if( strcmp(*args, "export")==0 ){ internal_export(); }else{ if( strcmp(*args, "source")==0 ){ internal_source(); }else{ if( strcmp(*args, "jobs")==0 ){ internal_jobs(); }else{ printf("%s","pasa los ifelse\n"); return 0; } } } } } int internal_cd(char **args){ printf("%s","cambio de directorio\n"); return 1; } int internal_export(char **args) { printf("%s","éste es el export\n"); return 1; } int internal_source(char **args) { printf("%s","éste es el source\n"); return 1; } int internal_jobs(char **args){ printf("%s","éste es el jobs\n"); return 1; } void main(){ char *line; while(read_line(&line)){//warning: imcompatible pointer type execute_line(&line);//warning: incompatible pointer type } //free line here?? }
your problem twofold.
first, design function take char *
expect accept char **
, like
char *read_line(char *line)
and
read_line(&line);
same goes execute_line()
also.
secondly,
malloc(sizeof(500));
is same as
malloc(sizeof(int));
what want instead
malloc(500);
as malloc()
takes argument size of memory allocated in bytes.
Comments
Post a Comment