我正在為作業系統課程作業制作一個 shell 模擬器。我們被要求添加一個“歷史”命令,當輸入該命令時,應列印用戶輸入的命令串列。
我決定使用歷史陣列來實作它,該陣列根據新命令的大小動態分配更多記憶體。
這是我的代碼:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 100
//comment
int main(void)
{
close(2);
dup(1);
char command[BUFFER_SIZE];
char* hist = NULL;
// int counter = 0;
while (1)
{
fprintf(stdout, "my-shell> ");
memset(command, '\0', BUFFER_SIZE);
fgets(command, BUFFER_SIZE, stdin);
if(strncmp(command, "exit", 4) == 0)
{
break;
}
//alocate memory for the current position in the hist array
if(hist == NULL){
hist = (char*)malloc(sizeof(char)*strlen(command));
}
else{
hist = realloc(hist,sizeof(char)*strlen(command));
}
strcat(hist,command);
printf("the size of the boy: %d\n",(int) strlen(hist));
// counter = strlen(command);
int pid = fork();
char *argv[BUFFER_SIZE];
char *pch;
pch = strtok(command, " \n");
int i;
for(i=0; pch != NULL; i ){
argv[i] = pch;
pch = strtok(NULL, " \n");
}
argv[i] = NULL;
int hasAmpersand = 0;
//check if the last entered character was '&'
if(*argv[i-1]=='&'){
// printf("entered &:");
hasAmpersand = 1;
//replace it with '\0'
argv[i-1] = NULL;
}
if(pid == 0){ //child process execute sys call
if(strncmp(argv[0],"history",7) == 0){
printf("%s\n", hist);
exit(1);
}
else{
execvp(argv[0], argv);
printf("\nbad syntax\n");
}
}
else{
if(!hasAmpersand){ //wait for child
while(wait(NULL) != pid);
}
}
}
free(hist);
return 0;
}
該實作適用于存盤在 hist 中的多達 6 個命令,但它因錯誤而崩潰
realloc(): invalid next size
aborted
我想知道是什么導致了這個問題,我很想得到解決它的建議。謝謝。
uj5u.com熱心網友回復:
realloc 的第二個引數應該是整個塊的新大小,而不僅僅是您“添加”到記憶體區域的資料大小。
hist = realloc(hist, currentHistSize sizeof(char)*strlen(command));
確保根據需要命名 currentHistSize。
uj5u.com熱心網友回復:
您需要為尾隨字串 terminator 留出空間'\0',因此在分配的大小上加一:
hist = malloc(sizeof(char)*strlen(command) 1);
realloc的引數也需要調整。此外,您可能希望在呼叫fgets后洗掉尾隨換行符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448227.html
