c - 在哪里以及如何正确释放 malloc 指针?

标签 c pointers malloc free

我现在正在学习 C 编程类(class),正在制作一个类似于 bash 的 shell。现在,我正在致力于实现管道。因此,我需要strndup管道命令在解析时不修改原始管道命令。最后,我尝试free malloc 'd 指针,但是我的程序无法正常工作。有人可以告诉我我做错了什么吗?下面是我的解析器的 while 循环的代码:

   while (pipeSeparatedCommand != NULL) {
        char *duplicateCmdForPiping = strndup(pipeSeparatedCommand, strlen(pipeSeparatedCommand)); // duplicates command
        pipeSeparatedCommand = strtok(NULL, "|"); // starts at the NULL Character that was tokenized
        char *token = strtok(duplicateCmdForPiping, " "); // finds the first space in the command, tokenizes the arguments by this space
        int index = 0;  // counts the number of commands and arguments

        while (token != NULL) {
            if ((input != NULL) || (output != NULL)) { // advances to the next argument if input or output is found (does not include them in args)
                token = strtok(NULL, " "); 
                continue;
            }

            commandArgsCount[index]++;
            commandArray[numberOfPipes][index] = token; // sets the argument index equal to the address of token (containing the token)
            token = strtok(NULL, " "); // token will search for the next delimiter from the last delimiter end spot
            index++;    
        }

        commandArray[numberOfPipes + 1][index] = NULL; // prevents the args array from collecting garbage in memory.

        if (pipeSeparatedCommand != NULL) // catches the zero case
            numberOfPipes++; // this begins at zero, increments if more pipes need to be added

        free(duplicateCmdForPiping);
        duplicateCmdForPiping = NULL;
    }

最佳答案

查看 strtok() 的手册页。它说该函数将返回“指向字符串中每个后续标记的开头的指针”。建议你改一下线路

    commandArray[numberOfPipes][index] = token;

    // make sure you `#include <string.h>`
    strcpy(commandArray[numberOfPipes][index], token);
    // OR
    commandArray[numberOfPipes][index] = strdup(token);

顺便说一句,请避免在 C/C++ 中使用驼峰式变量命名约定。它使您的代码极难阅读。

关于c - 在哪里以及如何正确释放 malloc 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59315129/

相关文章:

c - 函数内部使用malloc形成字符串时的段错误(11)

C 通过将数组中的任何指针转换为 void 指针来交换它们 K&R

c - Erlang nif不升级

C 代码、指针及其内容。考试题

c++ - 通过引用和指针传递参数

C - 指向数组中索引号的指针

C - malloc 的返回值可以像数组一样使用(对齐)吗?

c - 什么会导致 Valgrind 堆栈跟踪中出现奇怪的地址?

c++ - 如何使用 64 位而不是 32 位解决按位 seive?这两者有什么区别?

c - 如果在循环中多次调用 malloc() 和 realloc() 则多次 free()ing