I try to make the memory allocation dynamically for table that contains the strings.
In my case, I have to use it dynamically, because I don't know how rows and columns the program will get.
Here is my code for two function:
1.The first is allocating the memory for the table only.
2.The second should free all allocated memory.
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)
The result is "Runtime error" What am I doing wrong in the code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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<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<rows; i++) {
for(j=0; j<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<5; i++) {
for(j=0; j<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<5; i++) {
for(j=0; j<3; j++) {
printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
}
}
freeOptions(&options, 5, 3);
//here I want to check if the memory is freed
for(i=0; i<5; i++) {
for(j=0; j<3; j++) {
printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
}
}
return 0;
}