c - Why does this dynamic allocation of type char** and char* using malloc segfault? -
i don't understand why code segmentation faults. can work if define char** inside of function, allocate char**, point *commandsarray @ char**. can explain not understanding? 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)); }
you got precedence wrong: []
has higher precedence *
, *commandsarray[1]
accesses wrong address.
use parentheses force evaluation order, this
*commandsarray = malloc(2*sizeof(char*)); (*commandsarray)[0] = malloc(30*sizeof(char)); (*commandsarray)[1] = malloc(30*sizeof(char));
or use temporary variable use more readable syntax:
char** ret = malloc(2*sizeof(char*)); ret[0] = malloc(30*sizeof(char)); ret[1] = malloc(30*sizeof(char)); *commandsarray = ret;
note: casting malloc
unnecessary.