内存分配存在一些问题,分段错误

there is some issue with memory allocation, segmentation fault

我编写此代码是为了使用 linked 列表实现稀疏矩阵,但我不知道为什么会出现错误(分段错误)......有人可以帮助我吗。

我创建了一个 linked 列表数组,数组的索引表示矩阵的行,在 linked-list 中我存储了列和数据值。

下图中有一个 link 可以帮助您更好地理解代码。

https://i.stack.imgur.com/9rwH9.png

#include <stdio.h>
#include<stdlib.h>

struct Node {
  int col;
  int data;
  struct Node *next;
}*first;

void Create(struct Node **A, int m, int n) {
  struct Node  *t, *last;
  printf("Enter the elements of sparse matrix:\n");
  for(int i=0; i<m; i++){
    first = NULL;
    last = NULL;
    for(int j=0; j<n; j++){
      int val;
      scanf("%d", &val);
      if(val != 0){
        t= (struct Node *)malloc(sizeof(struct Node));
        t->col = j;
        t->data = val;
        t->next = NULL;

        if(first) 
          first = t;
        if(last)
          last->next = t;
        last = t;
      }
    }
    A[i] = first;
  }
  return;
}

void Display(struct Node **A, int m, int n){
  printf("\nSparse matrix is:\n");
  for(int i=0; i<m; i++){
    struct Node *p = A[i];
    for(int j=0; j<n; j++){
      if(p->col == j){
        printf(" %d ", p->data);
        if(p)
          p = p->next;
      }
      else printf(" 0 ");
    }
    printf("\n");
  }
}

int main() {
  int m=5, n=6;
  struct Node **A = (struct Node **)malloc(m * sizeof(struct Node));
  Create(A, m, n); 
  Display(A, m, n);
  return 0;
}

修复代码的三件事:

  • 分配时,应为内存句柄指向的数据类型分配 space,在您的情况下为 struct Node *:

    struct Node **A = malloc(m * sizeof(struct Node *));
    

    你可以这样写:

    struct Node **A = malloc(m * sizeof(*A));
    

    您还应该 free 使用后分配的所有数据。 (错误分配在这里没有坏处,因为你分配的比你需要的多,但如果你弄错了类型并且分配得太少,你就会大吃一惊。)

  • 插入第一个节点时,head为空,所以要检查的条件是:

    if (first == NULL) 
      first = t;
    

    您的原始代码从未向列表中添加任何节点。

  • 当您打印时,您访问 p,但 p 可能为空。这是您在访问 p:

    之前必须检查的第一件事
    if (p && p->col == j){
      printf(" %d ", p->data);
      p = p->next;
    }