C 中填充矩阵的 SIGSEV

问题描述 投票:0回答:1

我目前正在编写一个简单的代码,该代码应该将两个矩阵相乘,但是当我尝试创建大小超过 4 x 4 的矩阵时,我就遇到了 SIGSEV。

Matrix* allocate_matrix(size_t N) {
  int i, j;
  size_t MSIZE;
  Matrix* matrix = malloc(sizeof(int*) * (N * SIZE_MULT));
  MSIZE = N * SIZE_MULT;

  if (matrix == NULL) {
    perror("Error on malloc matrix");
    exit(2);
  }

  for (i = 0; i < MSIZE; i++) {
    matrix[i] = malloc(sizeof(int) * MSIZE);

    if (matrix[i] == NULL) {
      perror("Error on malloc matrix[i]");

      for (j = 0; j < i; j++) {
        free(matrix[j]);
      }

      free(matrix);

      exit(2);
    }
  }

  #if DEBUG
  printf("Matrix allocated");
  #endif

  return matrix;
}

这是我分配内存的方式 Matrix 类型定义为 int**

void fill_matrix(Matrix* m, size_t N) {
  size_t x;
  size_t y;
  size_t MSIZE;
  MSIZE = N * SIZE_MULT;

  for (y = 0; y < MSIZE; y++) {
    for (x = 0; x < MSIZE; x++) {
      m[y][x] = rand() % INT_LIMIT;

      #if DEBUG
      /*printf("Generated int: %d on [%ld][%ld]\n\n", m[y][x], y, x);*/
      #endif
    }
  }

  printf("Matrix filled");

  return;
}

这是将数字插入矩阵的功能。

请大家问一个愚蠢的问题,但我真的不知道出了什么问题..

该代码与其中一个完美配合,例如我成功创建了一个 10 x 10 的矩阵,但是一旦第二个出现并且必须填充它就会崩溃。伙计们,我需要一些提示。

arrays c matrix runtime-error
1个回答
0
投票
  1. 不要将指针隐藏在 typedef 后面
  2. ***
    指针通常表示不稳定、错误的代码
  3. 使用参数传递所有尺寸。避免奇怪的定义所有全局变量。
  4. 您可以使用数组指针
  5. sizeof
    中使用对象而不是类型

示例:

void *allocate_matrix(size_t rows, size_t cols) 
{
    int *matrix = malloc(sizeof(*matrix) * rows * cols);
}

void *fill_matrix(size_t rows, size_t cols, int (*matrix)[cols]) 
{
  for (size_t row = 0; row < rows; row++) 
  {
    for (size_t col = 0; col < cols; col++) 
    {
      matrix[row][col] = rand() % 1000;
    }
  }

  printf("Matrix filled\n");

  return matrix;
}


int main(void)
{
    size_t rows, cols;

    srand(time(NULL));

    rows = rand() % 20;
    cols = rand() % 20;

    int (*matrix)[cols] = allocate_matrix(rows, cols);

    if(matrix)
    {
        fill_matrix(rows, cols, matrix);
        for (size_t row = 0; row < rows; row++) 
        {
            for (size_t col = 0; col < cols; col++) 
            {
                printf("% 5d\t", matrix[row][col]);
            }   
            printf("\n");
        }
    }
    free(matrix);
}

https://godbolt.org/z/K1WTx3zPe

© www.soinside.com 2019 - 2024. All rights reserved.