Here is a shell program I wrote for honing my understanding on C pointer and array. This shell program has the functionalities of reading in commands (execute them in execvp()) and the history feature can store 10 commands (similar to Linux terminal) where "!!" returns latest command and execute, !Nth returns Nth command and execute, otherwise read command and store them in history array. When requested history command doesn't exist, relevant error message printed. For full code reference, see Shell_Program_C.
initialize()
method initialize each history character string array with letter 'e' ('e' means empty or string hasn't been assigned) so that I could later check that history string has value or not. readHist()
method assign each individual command to the history string array, char** hist
which has a size of 10.
My problem is:strcpy(hist[histC], tokens[count])
in readHist()
is returning 'bad access' here.
Expected behavior: each command should be copied to char** hist
as a string of char so that later requested command can be retrieved and executed.
char** initialize() {
char** hist = malloc(10 * sizeof(char *));
for (int i = 0; i < 10; ++i) {
hist[i] = (char *)malloc((MAX_LINE / 2) + 1);
for(int j = 0; j < (MAX_LINE / 2); j++) {
hist[i][j] = 'e';
}
}
return hist;
}
void readHist(char**hist, int histC ,char** tokens, int count) {
histC = (histC - 1) % 10;
for(int i = 0; i < count; i++) {
size_t strlenth = strlen(tokens[i]);
//strcat(hist[histC], tokens[count]);
if(count > 1) {
strcat(hist[histC], tokens[count]);
hist[histC][strlenth] = ' ';
} else {
printf("histC%d", histC);
strcpy(hist[histC], tokens[count]); // bad access or segmentation fault
hist[histC][strlenth] = '\0';
}
}
}