C - Dynamic memory allocation for table that contains strings
<p>I try to make the memory allocation dynamically for table that contains the strings.<br>
In my case, I have to use it dynamically, because I don't know how rows and columns the program will get.<br>
Here is my code for two function:<br>
1.The first is allocating the memory for the table only.<br>
2.The second should free all allocated memory.<br>
3.In the main function I'm allocating the memory for the string and copy the part of the predefined string (it's dummy code, for example only)</p>

<p>The result is "Runtime error"
What am I doing wrong in the code?</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

char *** buildOptions(int rows, int columns) {
    int i=0;
    printf("1...\n");
    char ***options = (char ***)malloc(rows * sizeof(char **));
    printf("2...\n");
    for(i=0; i&lt;rows; i++) {
        printf("3...\n");
        options[i] = (char **)malloc(columns * sizeof(char *));
        printf("4...\n");
    }
    return options;
}

void freeOptions(char ****options, int rows, int columns) {
    int i, j;
    for(i=0; i&lt;rows; i++) {
        for(j=0; j&lt;columns; j++) {
            if(*options[i][j])
                free(*options[i][j]);
        }
        if(*options[i]) {
            free(*options[i]);
        }
    }
    free(*options);
}

int main(void) {
    int i, j, k;
    char * str = "123456789abcdefghjkl\0";
    char ***options = buildOptions(5, 3);
    printf("Starting...\n");
    for(i=0; i&lt;5; i++) {
        for(j=0; j&lt;3; j++) {
            options[i][j] = (char *)calloc((i+j+2)+1, sizeof(char));
            strncpy(options[i][j], str, i+j+2);
        }
    }

    for(i=0; i&lt;5; i++) {
        for(j=0; j&lt;3; j++) {
            printf("&gt;&gt;options[%d][%d]=%s&lt;&lt;\n", i,j, options[i][j]);
        }
    }

    freeOptions(&amp;options, 5, 3);

    //here I want to check if the memory is freed
    for(i=0; i&lt;5; i++) {
        for(j=0; j&lt;3; j++) {
            printf("&gt;&gt;options[%d][%d]=%s&lt;&lt;\n", i,j, options[i][j]);
        }
    }


    return 0;
}
</code></pre>