0

I am trying to create a three dimensional struct array using malloc in c on MSVC. It compiles without error but when i debug it it gives an error after initializing some elements.

declaration:

typedef struct table_info
{
    unsigned long size;
    char code[33];
    char path[300];
}table_info;

table is a global variable and is defined as:

struct table_info ***table=NULL;

malloc and initialize table:

char garb[33] = { '\0' };
char garb_path[300] = { '\0' };

table = (table_info***)malloc(ROWS* sizeof(**table));

for (int m = 0; m < ROWS; m++)
{
    table[m] = (table_info**)malloc(COLS* sizeof(*table[m]));
    for (int j = 0; j < COLS; ++j)
    {
        table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));
        for (int k = 0; k < DEPTH; ++k)
        {
            table[m][j][k].size = 0;
            strcpy_s(table[m][j][k].code, sizeof(table[m][j][k].code), garb);
            memcpy(table[m][j][k].path, garb_path, sizeof(garb_path));
        }
    }
}

Am I initializing it correctly? or what should I correct to make it work?

mch
  • 9,424
  • 2
  • 28
  • 42
John_D
  • 29
  • 6
  • 1
    `struct table_info ***table` ==> `struct table_info (*table)[COLS][DEPTH];` and `table = (table_info***)malloc(ROWS* sizeof(**table));` ==> `table = malloc(ROWS * sizeof *table);` and remove the other `malloc`s if you want a real 3D array. – mch Nov 30 '17 at 09:47
  • [Three stars](http://wiki.c2.com/?ThreeStarProgrammer) very often signal a design mistake. – Antti Haapala -- Слава Україні Nov 30 '17 at 09:57

1 Answers1

1

The size passed to malloc is incorrect in the following line:

table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));

sizeof(table[m][j]) is just sizeof(**table), which is sizeof(table_info *). It should be sizeof(table_info), or alternatively sizeof(*table_info[m][j]) or sizeof(***table_info).

You also don't need to cast the result of malloc, which is generally frowned upon today (at least in C). See this post for more info.

So the following should work (in C):

table[m][j] = malloc(DEPTH * sizeof(*table[m][j]));
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • i am casting because otherwise MSVC gives me error, saying i cant assign a void* to a struct pointer. but I think your solution has worked. let me check it one more time and get back to you – John_D Nov 30 '17 at 10:00
  • If the cast is required, you are compiling a C++ program, not a C program. – mch Nov 30 '17 at 10:01
  • @mch Ah, ok - I was keying in on the C tag. – Tom Karzes Nov 30 '17 at 10:03
  • @TomKarzes my comment was a hint for the OP that he probably does not write a C program ;) – mch Nov 30 '17 at 10:04
  • you are right @mch I was compiling a c program as c++. Thanks. – John_D Nov 30 '17 at 10:19