3

我有以下代码,我对为什么会出现分段错误感到有些困惑。

typedef struct {
  int tag;
  int valid;
} Row;

typedef struct {
  int index;
  int num_rows;
  Row **rows;
} Set;

/* STRUCT CONSTRUCTORS */

// Returns a pointer to a new Sow.
// all fields of this row are NULL
Row* new_row() {
  Row* r = malloc(sizeof(Row));
  return r;
}

// Returns a pointer to a new Set.
// the set's index is the given index, and it has an array of
// rows of the given length.
Set* new_set( int index, int num_rows, int block_size ) {
  Set* s = malloc(sizeof(Set));
  s->index = index;
  s->num_rows = num_rows;

  Row* rows[num_rows];
  for (int i = 0; i < num_rows; i++) {
    Row* row_p = new_row();
    rows[i] = row_p;
  }
  s->rows = rows;

  return s;
}

/* PRINTING */

void print_row( Row* row ) {
  printf("<<T: %d, V: %d>>", row->tag, row->valid);
}

void print_set( Set* set ) {
  printf("[ INDEX %d :", set->index);


  for (int i = 0; i < set->num_rows; i++) {
    Row* row_p = set->rows[i];
    print_row(row_p);
  }

  printf(" ]\n");
}


int main(int argc, char const *argv[]) {

  Set* s = new_set(1, 4, 8);
  print_set(s);


  return 0;

}

基本上 aSet有一个指向Rows 数组的指针。我认为Row* row_p = set->rows[i];这是从一组中获取行的正确方法,但我一定遗漏了一些东西。

4

2 回答 2

4

Row*您正在分配s的本地数组

  Row* rows[num_rows];
  for (int i = 0; i < num_rows; i++) {
    Row* row_p = new_row();
    rows[i] = row_p;
  }
  s->rows = rows;

并让rows指针Set指向那个。函数返回后,本地数组不再存在,因此s->rows是一个悬空指针。在函数返回后仍然有效的内存必须分配给malloc(或其表亲之一)。

于 2012-11-26T20:34:19.207 回答
1

s->rowsrows在函数中分配了局部变量的地址new_set(),这意味着返回时s->rows是一个悬空指针new_set()。动态分配一个数组Row*来纠正:

s->rows = malloc(num_rows * sizeof(Row*));
if (s->rows)
{
    /* for loop as is. */
}

请记住,s->rows及其元素必须是free()d。

于 2012-11-26T20:34:10.000 回答