Malloc/realloc 只适用于无用的 printf

Malloc/realloc only works with useless printf

我正在尝试通过字符“|”对 argv 进行分词和 return 指针分别用于每个命令,例如:

如果 argv = "./a ls -a '|' grep png",我需要 cmd[0] 指向 ls 并且 cmd[1] 指向 grep。我写了下面的代码,但是,不知何故,只适用于第 20 行无用的 printf:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

char*** tokenizer(char** command, int argc){
    int token_amount = 0;

    char ***cmd = (char***) malloc(1 *sizeof(char**));
    cmd[0] = &command[0];

    for(int i = 0; i < argc; i += 1){
        //For each founded '|', cmd receives the next position of command
        if(!strcmp(command[i], "|")){
            token_amount += 1;
            cmd = realloc(cmd, token_amount *sizeof(*cmd));
            cmd[token_amount] = &command[i + 1];
            command[i] = NULL;
        }
        printf("\n");
    }
    command[argc] = NULL;
    return cmd;
}

int main(int argc, char** argv){
    char **command, ***cmd = NULL;

    //command doesn't receives the name of the executable
    command = &argv[1];
    cmd = tokenizer(command, argc - 1);
    
    //Testing
    for(int i = 0; i < 4; i += 1){
        printf("%s\n", cmd[i][0]);
    }
    //Testing
    execvp(cmd[0][0], cmd[0]);
    
    return 0;
}

如何避免此 printf?

这两行有问题:

cmd = realloc(cmd, token_amount *sizeof(*cmd));
cmd[token_amount] = &command[i + 1];

调用 realloc 后,cmd 的有效索引为 0token_amount-1。但是下一行使用 token_amount 作为索引,这是越界的。您可能想使用 token_amount-1 作为索引。