Home > Back-end >  can't access some elements in malloc generated 2D array
can't access some elements in malloc generated 2D array

Time:10-12

I'm trying to make a 2D array in C with malloc for "hash map" project but as usual. something happend !

basically I have an issue of accessing the 3rd element of the 1st array arr[0][3], it's super weird (at least to me) ,so let me show you the code

1- create 2D array:

int main(void){
    char*** table;
    table = malloc(sizeof(char*) * 10);
    //create array inside table
    table[0] = malloc(sizeof(char) * 20);
    
    return 0;
}

2- assign some strings to 1st array table[0]:

    table[0][1] = "test1";
    table[0][2] = "test2";
    table[0][3] = "test3";
    table[0][4] = "test4";
    ...
    table[0][n] = "testn";

3- now the magic happens:

   // 10 => n >= 0;
   printf("%s", table[0][n]);

returns -> malloc(): corrupted top size Aborted (core dumped)

in that moment I tried everything a noob would do , so somehow I figured out that the 3rd string test3 is the problem. so if I remove the table[0][3] line, all works great !!

    table[0][1] = "test1";
    table[0][2] = "test2";
    //table[0][3] = "test3";
    table[0][4] = "test4";
    ...
    table[0][n] = "testn";
    
    // 10 => n >= 0;
    printf("%s", table[0][n]);

returns => "testn";

EDIT for Vlad From Moscow that works:

   for(int i=0; i<10; i  {
       table[0][n] = "test";
       //here works
       printf("%s", table[0][n];
   }
   //here also works fine
   printf("%s", table[0][3];

CodePudding user response:

You declared the pointer table like

char*** table;

So the expression table[0] used in this statement

table[0] = malloc(sizeof(char) * 20);

has the type char ** and you allocated memory for 20 characters.

If sizeof( char * ) is equal to 8 then the allocated memory can accommodate only two pointers of the type char *. If sizeof( char * ) is equal to 4 then the allocated memory can accommodate only 5 pointers of the type char *.

You need to do something like the following

char*** table;
table = malloc(sizeof(char**) * 10);
//create array inside table
for ( size_t i = 0; i < 10; i   )
{
    table[i] = malloc(sizeof(char *) * 20);
}

These memory allocations will simulate a two dimensional array of the type char * table[10][20].

On the other hand, you could at once allocate memory for a two-dimensional array like

char * ( *table )[20] = malloc( sizeof( char *[10][20] ) );
  • Related