Search code examples
csegmentation-faultdouble-pointer

Casting Double Pointer and How to utilize in C


Here is basically a simple code of double pointer and what I am trying to use:

int argsCount = 1;
char **cmdArgs1 = malloc((argsCount + 1)*sizeof(char*));

I want to input values into the cmdArgs1 and here is basically what I am doing and causing seg fault

for(counter = 0; counter < argsCount; counter++)
{
    strcpy(cmdArgs1[counter],"ls");
}

I'm thinking that I can't use "cmdArg1[counter]" to copy to "ls" because the double pointer doesn't work that way? I'm not sure...

Even I think it's a bit vague, but I don't know how to phrase the question well, I will try to update based on the comment. Thx!


Solution

  • Your cmdArgs1 is a pointer to a pointer, meaning that it is not enough to allocate space for the array itself. You need to allocate space for the individual arrays of characters (or for the individual C string).

    You can do it in a separate call of malloc

    for(counter = 0; counter < argsCount; counter++)
    {
        cmdArgs1[counter] = malloc(strlen("ls")+1); // +1 for null terminator
        strcpy(cmdArgs1[counter], "ls");
    }
    

    or with strdup:

    for(counter = 0; counter < argsCount; counter++)
    {
        cmdArgs1[counter] = strdup("ls");
    }
    

    In both cases your program is liable for freeing the elements of the array before freeing the array itself:

    for(counter = 0; counter < argsCount; counter++)
    {
        free(cmdArgs1[counter]);
    }
    free(cmdArgs1);