我想做的是在我的 shell 程序中开发一个历史命令。因此,每当用户写入历史记录时,最后输入的 10 个命令就会显示在屏幕上

这是我的一段代码..

  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;
}

要打印历史记录,我的意思是 cmdsHistory,这是代码:

 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]);
        }
    }

然后每当用户写入历史记录时,我都会循环遍历 cmdsHistory 并打印结果。

我无法将 *cmdHistory (用户输入的 set 命令)放入 **cmdsHistory 数组中的问题。

有什么帮助吗?

有帮助吗?

解决方案

一项解决办法就是改变

char **cmdsHistory;

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

但依然是你的 程序内存泄漏, ,通过调用 strdup 并重置 i as 0 一个循环后。请修复它。

修复泄漏就像

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

确保初始化所有指针 NULL 启动时。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top