Why is my 2D array causing a bus error in C?

I am trying to create a simple 2D array in C, but it seems to be facing some memory issues. My setup is simple enough and I can’t say what happened. I admit that my understanding of pointers is not enough, but I still think this should work. 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 it starts.

+3
source share
3 answers

series_of_datais an invalid pointer - you are not assigning it. When you try to assign its memory location ( *series_of_data = ...), it puts the material in a random place that probably won't do what you want. You should indicate series_of_datasomewhere useful, for example.

series_of_data = (DATUM **)malloc(16 * sizeof(DATUM *))

16 DATUM * .

+1

series_of_data .

2D-, , -, , , Iliffe, C, h * w , ( ):

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);
}

, , [] []. +/- 3% DATUM * +.

+6

series_of_data *series_of_data.

, series_of_data , - :

series_of_data = malloc(n*sizeof(DATUM*));

n - series_of_data.

*series_of_data.

+1

All Articles