Question

What I want to do is developing a history command in my shell program. So, whenever the user write history, the last 10 command entered with be displayed on the screen

This is my piece of code..

  int i;
  char cmd[4096];
  int cmdHisC =0; 
  char *cmdHistory;
  char *cmdsHistory[10];


      while(1) {
    /*** Read input from shell ***/
        fgets(cmd,4096,stdin);
if(strcmp(cmd,"") != 0)
{
    if((cmdHistory= strdup(cmd)) != NULL)
    {
        if (cmdsHistory[cmdHisC] != NULL) 
        free(cmdsHistory[cmdHisC]);

        cmdsHistory[cmdHisC] = cmdHistory;
        cmdHisC++;
    }       
    else
    fprintf(stderr, "Error, Cannot save this command in the history pointer: Out of memory\n");

    if(cmdHisC>9)
        cmdHisC=0;
}

to print the history I mean the cmdsHistory, this is the code:

 if(strcmp(argsCmd[0], "history")==0)
    {
       for(int n = 0; n<10 ; n++) 
        {
        if(cmdsHistory[n] != NULL)
        printf("History command  %d: %s\n", n, cmdsHistory[n]);
        }
    }

Then whenever the user write history, I will loop through the cmdsHistory and print the results.

The problem that I couldn't make the *cmdHistory (the sets command that the user entered) into an array of **cmdsHistory.

Any help please?

Was it helpful?

Solution

One fix would be changing

char **cmdsHistory;

to

char *cmdsHistory[10]; //or any desire number/macro

But still your program leaks memory, by calling strdup and resetting i as 0 after a cycle. Please fix it though.

Fix for leak would be like

if (cmdsHistory[cmdHisC]) {
    free(cmdsHistory[cmdHisC]);
    cmdsHistory[cmdHisC] = cmdHistory;
}

Make sure you initialize all pointers to NULL on start up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top