Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my 2D array cause a bus error in C?

I'm attempting to create a simple 2D array in C but apparently running into some memory trouble. My setup is simple enough and I can't tell what's wrong. I admit that my understanding of pointers is insufficient, but I still think this should be working. Can anyone see the flaw here?

typedef unsigned int DATUM;
DATUM **series_of_data;
void initialize_data()
{
    *series_of_data = (DATUM *) malloc(1024 * sizeof(DATUM));
}

This causes my program to crash with a bus error when I run it.

like image 569
Josh Leitzel Avatar asked Feb 17 '26 07:02

Josh Leitzel


1 Answers

series_of_data is actually not allocated.

You have various way to allocates a 2D array, either using the array of rows model whcih has bad cache coherency and thus has usually bad performances or to use the Iliffe vector adviced in Numerical recipes in C that consists in allocating one huge h*w memory block and a side pointer array which contains the beginning of your rows (or columns) :

DATUM** alloc_array( int h, int w )
{
  int i;
  DATUM** m = (DATUM**)malloc(h*sizeof(DATUM*));
  m[0] = (DATUM*)malloc(h*w*sizeof(DATUM));
  for(i=1;i<h;i++) m[i] = m[i-1]+w;
  return m;
}

void release_array(DATUM** m)
{
  free( m[0] );
  free( m);
}

int main()
{
  int r,c;
  DATUM** tab;
  int width  = 5;
  int height = 3;
  tab = alloc_array(height, width); /* column first */

  for(r = 0;r<height;++r)
   for(c = 0;c<width;++c)
    tab[r][c] = (1+r+c);

  for(r = 0;r<height;++r)
  {
    for(c = 0;c<width;++c)
    {
      printf("%d\t",tab[r][c]);
    }
    puts("");
  }
  release_array(tab);
}

Data are nicely packed in memory, so cache are happy and you keep the [][] access pattern. As a matter of speed this is in +/-3% speed of the classical DATUM* + polynomial access method.

like image 162
Joel Falcou Avatar answered Feb 18 '26 23:02

Joel Falcou