c - 如何释放我在函数中返回的变量的内存

标签 c malloc fork

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/

相关文章:

c - 如何正确退出子进程?

c - 在 C 中解析字符串

c - Realloc 读取 C 中的大文本文件

c - 使用 fork 两次 - 奇怪的行为

Xcode 4 : Can't use Enable Guard Malloc due to dylib error for iPad simulator

c - 为什么它的 c 指针在这里不起作用?

python - 在工作进程启动之前将数据放入输入队列时,工作进程在 requests.get() 上崩溃

c - 期待编译错误

java - 共享库分配的 JNA 空闲内存

c - 在另一个字符串中搜索最右边的字符串 - 在 c 中