#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LINE 80 /* Maximum length of command*/
struct memList
{
char commandName[41];
char restCommandName[41];
struct List *next;
};
void addToList(char [], char [], int);
int main()
{
char *args[MAX_LINE/2+1]; /* Command Line Argument*/
int should_run=1, status, i, num;
pid_t pid;
char str[41], teststr[41];
const char delimiter[2]=" ";
char *token;
while(should_run)
{
i=0;
printf("osh>");
fflush(stdout);
fgets(str, sizeof str, stdin);
str[strlen(str)-1]='\0';
token=strtok(str, " ");
while(token)
{
args[i]=strdup(token);
printf("args[%d]=%s\n", i, args[i]);
i++;
token=strtok(NULL, " ");
}
if(args[0]=="history")
{
addToList(args[0], str, 1);
}
else
{
addToList(args[0], str, 0);
}
pid=fork();
if(pid<0) // error in creating child process
{
printf("\tError in creating child process\n");
}
else if(pid==0) //child process will execute this block
{
printf("\tChild running it's block\n");
execvp(args[0], args);
exit(1);
}
else //parent process will execute this block
{
pid=wait(&status);
printf("\tNow Parent resumes\n");
if(!strcmp(args[0], "exit"))
{
should_run=0;
}
}
}
return 0;
}
void addToList(char cmd[], char restCmd[], int flag)
{
int i;
struct memList *head=NULL; //In this function node is created
struct memList *ptrNode=NULL; // and added to the list
struct memList *temp=NULL;
ptrNode=(struct memList *)malloc(sizeof(struct memList));
memset(ptrNode, 0, sizeof(struct memList));
strcpy(ptrNode->commandName, cmd);
strcpy(ptrNode->restCommandName, restCmd);
if(head==NULL)
{
head=ptrNode;
}
else
{
ptrNode->next=head->next;
head=ptrNode;
}
if(flag) //if flag=1 i.e. if args[0]=history then the whole list will get printed
{ //this block of code shows error
temp=head; //assignment for incompatible pointer type
while(temp!=NULL)
{
printf("%d %s", i, temp->commandName);
temp=temp->next;
}
}
}
如果我的代码中存在任何其他现有内存泄漏以及我将args [0]作为参数传递给函数addToList(),请告诉我。那是对的吗。如果没有,那我该怎么做呢。
答案 0 :(得分:0)
问题是struct List *是一个与struct memList *不同的指针类型,所以temp = temp-&gt; next;给出编译器错误。 (在gcc-4.7.2中,错误信息是:在分配时无法将'List *'转换为'memList *')
按如下方式更改struct memlist声明:
struct memList
{
char commandName[41];
char restCommandName[41];
struct memList *next; // instead of struct List *next;
};