Reputation: 67
I'm having trouble with a project for university that consists in simulating a shell. The user types a command and the program divides the line in tokens and checks if one of them is an internal command, such as cd, export, jobs and source. Then prints the tokens and a basic explanation of the command that has been found in that line. When I run it on CodeBlocks everything works fine, but when I compile it on NetBeans in Linux, it reports several warnings, which I explain in the code and when I run it this message appears: Segmentation Fault (core dumped). I've been researching about it and I've found that this has to do with memory permissions (accessing a part of the memory you are not allowed to access). I can't find a way to solve it, but I hope someone here can help 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 from integer without a cast
while(token!=NULL){
printf("token%i: %s\n",n,token);
*args=token;
n++;
*args++;
token=strtok(NULL," ");// warning: assignment makes pointer from integer without a cast
}
printf("token%i: %s\n",n,token);
*args=token;
return n;
}
char *read_line(char *line){ //expecting argument char* but argument is of type char**
printf("%s ",PROMPT);
*line = malloc(sizeof(500));//warning: assignment makes pointer from integer without a cast
fgets(line,500,stdin);
return line;
}
int execute_line(char *line){//expecting argument char* but argument is 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??
}
Upvotes: 0
Views: 121
Reputation: 134286
Your problem is twofold.
First, you design the function to take a char *
but expect it to accept a char **
, like
char *read_line(char *line)
and
read_line(&line);
Same goes for execute_line()
also.
Secondly,
malloc(sizeof(500));
is just the same as
malloc(sizeof(int));
What you want instead is
malloc(500);
as malloc()
takes the argument for the size of memory to be allocated in bytes.
Upvotes: 1