Search code examples
cunixsunsparcbus-error

Bus Error only when running on Solarix Unix Box


It compiles up and runs on my Linux box(Ubuntu) as well as other linux boxes both x86 and x64 but on a SunOS Generic_142900-02 sun4u sparc unix box, it crashes on the line

matrix->col_head[i] = col_h;

with a bus error, Also, when i compile it up with GCC -G, GDB fails to find any debuging symbols

Here is the Code:

typedef unsigned short short_u;
typedef struct node{
  short_u         row;
  short_u         col;
  int             value;
  struct node*    row_l;
  struct node*    col_l;
}node_t;

typedef struct matrix{
  short_u     N;
  node_t**    row_head;
  node_t**    col_head;
}matrix_t;

matrix_t* init_matrix(int N){
  matrix_t* matrix = malloc(sizeof(matrix_t*));
  matrix->row_head = malloc(sizeof(node_t*)*N);
  matrix->col_head = malloc(sizeof(node_t*)*N);
  matrix->N = N;
  for (int i = 0; i < N; i++){
      /* row */
      node_t* row_h = malloc(sizeof(node_t*));
      row_h->col = 0;
      row_h->row = i+1;
      row_h->value = 0;
      row_h->col_l = row_h;
      if (i != 0)
          matrix->row_head[i-1]->row_l = row_h;
      matrix->row_head[i] = row_h;
      /* col */
      node_t* col_h = malloc(sizeof(node_t*));
      col_h->col = i+1;
      col_h->row = 0;
      col_h->value = 0;
      col_h->row_l = col_h;
      if (i != 0)
          matrix->col_head[i-1]->col_l = col_h;
      matrix->col_head[i] = col_h;
  }
  matrix->row_head[N-1]->row_l = matrix->row_head[0];
  matrix->col_head[N-1]->col_l = matrix->col_head[0];

  return matrix;
}

Solution

  • When you do

    matrix_t* matrix = malloc(sizeof(matrix_t*));
    

    you allocate space of a pointer to a matrix_t, which is not enough for the entire matrix_t. Your bus error is probably the result of accessing unallocated memory at matrix->row_head and matrix->col_head.

    You repeat this mistake in lines

      node_t* row_h = malloc(sizeof(node_t*));
    

    and

      node_t* col_h = malloc(sizeof(node_t*));
    

    The fact that you don't get a segfault on the Linux machines is a happy accident.