我对c指针有疑问。我正在构建自己的shell。根据valgrind,我有一个与指针有关的内存泄漏。我已经尝试了许多不同的方法来释放所有通常以段错误结束的内存。我的代码非常复杂,所以我不打算发布它。但基本上我的代码的一部分是:
void seperateCommands(char *input[]){
process *processArr[10];
char **currInstruction;
currInstruction = calloc(300 , sizeof(char *));
if(input[inputIndex] == NULL){
currInstruction[instructionIndex] = NULL;
//printString(currInstruction);
process *tempP;
tempP = (process *)calloc(1,sizeof(process));
tempP->instruction = currInstruction;
processArr[processIndex] = tempP;
processIndex++;
break;
}
}
job *j;
j = (job *) calloc(1,sizeof(job));
j->currProcess = processArr[0];
免费方法:
void free_job(job* j){
int i = 0;
if(j->currProcess != NULL){
free(j->currProcess->instruction);
}
if(j->currProcess != NULL){
free(j->currProcess);
}
if(j->twoProcess){
if(j->secondProcess != NULL){
free(j->secondProcess->instruction);
free(j->secondProcess);
}
}
for (i = 0; i < 300; i++){
free(j->instruction[i]);
}
free(j->instruction);
free(j);
}
两个结构:
typedef struct job{
char **instruction;
struct job* nextJob; //next active
pid_t pgid; //-1 if not set
int status; //0 if running, 1 if completed, 2 if stopped
struct process* currProcess; //max of 2 with pipes
struct process* secondProcess;
char state; //'F' if forground or 'B' if background
int twoProcess;
} job;
typedef struct process{
char **instruction; //current instruction to be executed
int *inputPipe;
int *outputPipe;
char *inputFile;
char *outputFile;
int status; //status
int completed; //1 if completed
char stopped; //1 if stopped
pid_t pid; //pid of process
} process;
typedef struct job{
char **instruction;
struct job* nextJob; //next active
pid_t pgid; //-1 if not set
int status; //0 if running, 1 if completed, 2 if stopped
struct process* currProcess; //max of 2 with pipes
struct process* secondProcess;
char state; //'F' if forground or 'B' if background
int twoProcess;
} job;
不知何故valgrind表明tempP和currProcess没有获得自由。但是,因为我通过创建作业来引用这些指针,所以最终使用free_job方法释放值。如果我尝试添加免费(tempP)或免费(currinstruction),我会得到一个段错误。任何帮助将非常感激。几个小时我一直在尝试不同的事情。
在基于概念的附注中,如果我有:
char **input;
char **sample = malloc(sizeof(char*) * 30);
input = sample;
free(input)
我还必须免费提供样品吗?
答案 0 :(得分:0)
你的意图不清楚,例如,在你的旁边的例子中,你似乎分配了一个30个字符的char数组。要做到这一点,你不需要做一个指针指针,这就足够了:
char *input;
char *sample = malloc(sizeof(char*) * 30);
input = sample;
free(input)
并且您不需要释放样本,但是当您将自由输入时,样本将被取消,因为它们引用相同的已分配块。因此,请勿尝试在免费(输入)&#39;
之后重复使用样本