1

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?

Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
user3340449
  • 15
  • 1
  • 7

1 Answers1

1

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.

Sakthi Kumar
  • 3,047
  • 15
  • 28
  • For initializing all the pointers to NULL at the beginning. Should I do like this? char *cmdsHistory[10]=NULL; char *cmdHistory=NULL; – user3340449 Feb 27 '14 at 09:13
  • just use a for loop to be simple. `for (i=0;i<10;i++) cmdsHistory[i] = NULL;` – Sakthi Kumar Feb 27 '14 at 09:14
  • Hi again, I discovered that I have another problem. Whenever I exceed 10 entries, and then type history as a command. I will get many strange numbers and then a message fault memory (core dumped)!! Any idea about this error – user3340449 Feb 27 '14 at 11:23