Search code examples
cdynamicsegmentation-faultmallocallocation

Why does this dynamic allocation of type char** and char* using malloc segfault?


I don't understand why this code segmentation faults. It can work if I define a char** inside of the function, allocate to that char**, then point *commandsArray at that char**. Can someone explain what I am not understanding? Thanks in advance.

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

void input_str_to_sngl_commands( char*** commandsArray );

int main()
{

    char** commandsArray_var;
    input_str_to_sngl_commands( &commandsArray_var );

return 0;
}

void input_str_to_sngl_commands( char*** commandsArray )
{
    *commandsArray = (char**) malloc(2*sizeof(char**));
    *commandsArray[0] = (char*) malloc(30*sizeof(char));
    *commandsArray[1] = (char*)malloc(30*sizeof(char));
}

Solution

  • You got the precedence wrong: [] has higher precedence than *, so *commandsArray[1] accesses a wrong address.

    Use parentheses to force evaluation order, like this

    *commandsArray = malloc(2*sizeof(char*));
    (*commandsArray)[0] = malloc(30*sizeof(char));
    (*commandsArray)[1] = malloc(30*sizeof(char));
    

    or use a temporary variable to use a more readable syntax:

    char** ret = malloc(2*sizeof(char*));
    ret[0] = malloc(30*sizeof(char));
    ret[1] = malloc(30*sizeof(char));
    *commandsArray = ret;
    

    Demo.

    Note: Casting malloc is unnecessary.