I am trying to implement the UNIX type shell. I have not implemented the shell creating a child process to run each command part, but this is just a code to break the string entered at the command prompt by the user into the appropriate arguments by using a space as a delimiter, which will then be passed to the file corresponding to the command (say ls -l) as command line arguments.
It runs alright on my Windows 7 OS, but when I run it on Ubuntu with my input string as "ABC XYZ WGH", I get an error, saying "Undefined symbol 'printf' version ABC." Please help me understand, where I am going wrong?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int arguments(char str[],char *** args)
{
char *s;
int num;
int i;
s=(char*)calloc(strlen(str)+1,sizeof(char));
strcpy(s,str);
if(strtok(s," ")==NULL)
num=0;
else
{
num=1;
while(strtok(NULL," ")!=NULL)
num++;
}
strcpy(s,str);
**args=strtok(s," ");
if(num)
{
for(i=1;i<num;i++)
*((*args)+i)=strtok(NULL," ");
}
return num;
}
int main()
{
char buffer[256];
char **arg;
int args;
int i;
while(true)
{
gets(buffer);
if(!strcmp(buffer,"STOP"))
break;
args=arguments(buffer,&arg);
printf("%d\n",args);
for(i=0;i<args;i++)
printf("%s\n",arg[i]);
}
return 0;
}
Under gdb, I get:
Program received signal SIGSEGV, Segmentation fault. 0x00000000004007a8 in arguments (str=0x7fffffffe010 "", args=0x7fffffffe000) at uc:20 20 **args=strtok(s," ");
ie, you use a pointer that points to a pointer that points to nothing usable: this is undefined behaviour, and it may be why you get strange things like ""Undefined symbol 'printf' version ABC.", or segmentation fault under gdb.
I suggest you rewrite the fonction arguments()
with less indirection levels (and a better use of strtok()
=), but for now this code may do what you want:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 32
int arguments(char str[],char **args)
{
char *s;
int num;
int i;
s=malloc(strlen(str)+1);
strcpy(s,str);
if(strtok(s," ")==NULL)
num=0;
else {
num=1;
while(strtok(NULL," ")!=NULL)
num++;
}
strcpy(s,str);
// **args=strtok(s," ");
*args=strtok(s," ");
if(num)
{
for(i=1;i<num;i++)
// *((*args)+i)=strtok(NULL," ");
args[i] = strtok(NULL," ");
}
return num;
// note. 's' is not free()'d ..
}
int main()
{
char buffer[256];
char *arg[MAX];
int args;
int i;
while(1)
{
gets(buffer);
if(!strcmp(buffer,"STOP"))
break;
args=arguments(buffer, arg);
printf("%d\n",args);
for(i=0;i<args;i++)
printf("%s\n",arg[i]);
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.