Search code examples
cmallocstructureruntime-errordynamic-memory-allocation

Getting runtime error when i access (table->array[i][i]).min = (table->array[i][i]).max = arr[i];


I am using DP to fill a table which contains maximum & minimum item from index i to index j in an array. Whether this approach is efficient or not, is not an issue to me.
Consider the below code snippet:

typedef struct Slot
{
    int min;
    int max;
}Slot;

typedef struct Table
{
    Slot* *array;
    int size;
}Table;

Table* createTable( int size )
{
    Table* table = malloc( sizeof( Table ) );

    if( !table )
            return NULL;

    table->array = ( Slot(*)[size] ) malloc( size * size * sizeof( Slot ) );

    if( !(table->array) )
                    return NULL;

    table->size = size;

    return table;
}

void foo( int arr[], int size )
{
    Table* table = createTable( size );

    if( table == NULL )
    {
            printf( "Out of memory" );
            return;
    }

    int i;

    for( i = 0; i < size; ++i )
            (table->array[i][i]).min = (table->array[i][i]).max = arr[i]; <----------
}

I am getting runtime error. When i comment the below two statements, it runs fine.

for( i = 0; i < size; ++i )
            (table->array[i][i]).min = (table->array[i][i]).max = arr[i]; <----------

Why it is showing runtime error?


Solution

  • The malloc of your 2D array Slot is wrong:

    table->array = ( Slot(*)[size] ) malloc( size * size * sizeof( Slot ) );
    

    instead of this you should do this:

     table->array = (Slot**) malloc(sizeof(Slot*));
       for (int i = 0; i < ArraySizeX; i++)
            table->array[i] = (Slot*) malloc(ArraySizeY*sizeof(Slot));
    

    or if you wish to do it in one malloc call, however then only have a Slot* in your Table:

    table->array = (Slot*) malloc(SizeX * SizeY * Sizeof(Slot));
    

    This will allocate your double array properly.

    Then also, this construct:

      for( i = 0; i < size; ++i )
         (table->array[i][i]).min = (table->array[i][i]).max = arr[i];
    

    you should really do one assignment at a time:

      for( i = 0; i < sizeX; ++i )
      {
          (table->array[i][i]).max = arr[i];
          (table->array[i][i]).min = (table->array[i][i]).max;
      }