Helo,我有一个作业,要使用 fork()、malloc() 和 execv() 用 C 语言编写一个简单的 shell,但遇到以下问题: 我需要释放变量的内存,我将在函数中返回该变量
char** parse_cmdline(const char* line){
int size = strlen(line);
char** array_of_strings = malloc((sizeof(char*)*(size)))
char* pch = strtok(line," \n\t\r");
int co = 0;
int co2;
while (pch != NULL)
{
array_of_strings[co]=(char*)malloc((sizeof(char)*strlen(pch))+1);
strcpy(array_of_strings[co], pch);
pch = strtok (NULL, " \n\t\r");
++co;
}
array_of_strings[co] = NULL;
return array_of_strings; //that's the variable I need to free
}
这是整个程序
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
char** parse_cmdline(const char* line){
int size = strlen(line);
char** array_of_strings = malloc((sizeof(char*)*(size)));
char* pch = strtok(line," \n\t\r");
int co = 0;
int co2;
while (pch != NULL)
{
array_of_strings[co]=(char*)malloc((sizeof(char)*strlen(pch))+1);
strcpy(array_of_strings[co], pch);
pch = strtok (NULL, " \n\t\r");
++co;
}
array_of_strings[co] = NULL;
return array_of_strings;
}
int main(int argc, char *argv[]){
char line[512];
printf("Welcome to My shell!\n");
while(1){
printf(">$");
gets(line);
pid_t pid = fork();
if (pid == -1){
perror("");
}else if(pid == 0){
execvp(parse_cmdline(line)[0], parse_cmdline(line));
}else{
wait(pid);
}
}
return 0;
}
请帮帮我
最佳答案
如果 execvp()
成功,则无需释放缓冲区,因为 execvp()
会将进程内存镜像替换为您要执行的内存镜像。这意味着旧进程的内存映射将被丢弃,从而释放任何分配的缓冲区。
但是如果 execvp()
失败,您仍将处于当前进程中,并且可以释放缓冲区:
else if(pid == 0)
{
char **cmdline = parse_cmdline(line);
if (execvp(cmdline[0], cmdline)<0)
{
for (int i=0;*cmdline[i];i++)
free(cmdline[i]);
free(cmdline);
}
}
关于c - 如何释放我在函数中返回的变量的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889020/