Home > OS >  Array of Commands in C
Array of Commands in C

Time:02-28

I am trying to create a char** called history that holds an array of commands like this:

do thing1
do thing2
do thing3
do thing4

The commands are input by the user one at a time and I want them to be added to this history array as they come. At the end of the program I want to print the commands back to the user in the order they were written.

Here is my code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int BUFFER = 50;
int MAX_ARGS = 100;
int HISTORY_SIZE = 50;

int bufferSize;

//Read in line from user 
char* getLine(void){

    char* line = NULL;
    size_t len = 0;
    size_t lineSize = 0;
    lineSize = getline(&line, &len, stdin);
    return line;
}

int main(){

    //declare variables
    char *line, *lineCopy;
   
    //history structure
    char* history[100];
    int historyCount = 0;

    do{

        //main program loop

        //get command 
        printf("# ");
        line = getLine();

        //copy command
        strcpy(lineCopy, line);

        history[historyCount] = lineCopy;
        historyCount  
        

    }while(historyCount < 4); //while status

    for(int i = 0; i < historyCount; i  ){
        printf("%d: %s\n", i, history[i]);
    }

    return 0;
}

With this, every value in the array is just set to the last command entered and the output is

do thing4
do thing4
do thing4
do thing4

I understand that this is just because I am pointing it to the memory address of lineCopy each time but I'm not sure how to fix it and get

do thing1
do thing2
do thing3
do thing4

CodePudding user response:

  1. String copy to invalid memory.

  2. As every call to wrapper getLine() will get you new memory buffer you can just use the buffer right away without duplication.

    //copy command
    //strcpy(lineCopy, line);

    history[historyCount] = line;
    historyCount  

    //or just
    history[historyCount  ] = getLine();
  1. You need to free all line buffers stored history[] once you're done with it.

  2. You're not checking the return status of getline() in getLine() wrapper.

CodePudding user response:

you just need to make a copy of the string

history[historyCount] = strdup(line);

CodePudding user response:

One issue is you're copying the line over to lineCopy but you never allocated memory for lineCopy.

And have an array of 100 char pointers, each one pointer to lineCopy which actually isn't what you want. Because lineCopy will always point to the most recently string in your case. Which is why every command in your history essentially ends up being the same.

  • Related