Ad

Malloc/realloc Only Works With Useless Printf

- 1 answer

Im trying to tokenizer the argv by the character '|' and return pointers for each command separately, for example:

If argv = "./a ls -a '|' grep png", I need that cmd[0] point to ls and cmd[1] point to grep. I wrote the code below, but, somehow, only works with a useless printf, on line 20:

#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;
}

How can I avoid this printf?

Ad

Answer

There is a problem with these two lines:

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

After calling realloc, the valid indices into cmd are 0 through token_amount-1. But the very next line uses token_amount as an index, which is out of bounds. You probably want to use token_amount-1 as the index.

Ad
source: stackoverflow.com
Ad