微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 bin 排序算法中获取 malloc 断言错误

如何解决在 bin 排序算法中获取 malloc 断言错误

这是一个 bin 排序程序。我在网上找到了其他方法,但我的老师认为我们是这样的。我是编程初学者,请帮我写代码

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

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


//Print array function
void printArray(int arr[],int n){
  for(int i=0; i<n; i++)
    printf("%d ",arr[i]);
  printf("\n");
} 

//findMax function for count and bin/bucket sort
int findMax(int arr[],int n){
  int max = INT_MIN;
  for(int i=0; i<n; i++){
    if(arr[i]>max) max=arr[i];
  }
  return max;
}

//insert function for bins sort
void Insert(struct Node *Bins[],int index){
  struct Node *t;
  t=(struct Node*)malloc(sizeof(struct Node));
  t->data = index;
  t->next=NULL;
  if(Bins[index] != NULL){
    while(Bins[index] == NULL)
      Bins[index]= Bins[index]->next;
    Bins[index]->next = t;
  }
  else
    Bins[index] = t;
}

//delete function for bin/bucket sort
int Delete(struct Node *Bins[],int i){
  int x;
  if(Bins[i]->next !=NULL){
    struct Node *temp;
    temp=(struct Node*)malloc(sizeof(struct Node));
    temp=Bins[i]->next;
    x=Bins[i]->data;
    free(Bins[i]);
    Bins[i] = temp;
  }
  else{
    x = Bins[i]->data;
    free(Bins[i]);
  }
  return x;
}

// bin/bucket sort
void BinSort(int arr[],int n){
  int max,i,j;
  struct Node **Bins;
  Bins =(struct Node**)malloc(sizeof(struct Node*));
  max = findMax(arr,n);
   for(i =0; i<max+1; i++) 
    Bins[i] = NULL;
  for(i=0; i<n; i++)
    Insert(Bins,arr[i]);
  i=j=0;
  while(i < max+1){
    while(Bins[i] != NULL)  
      arr[j++] = Delete(Bins,i);
  i++;
  }
}

int main(){
  int n=10;
  int arr[] = {8,5,7,3,2,6,4,11,5};
  BinSort(arr,n);
  printArray(arr,n);
  return 0;
}

该程序使用辅助数组来维护元素的数量,但使用链表,我相应地编写了插入和删除函数

解决方法

线

Bins =(struct Node**)malloc(sizeof(struct Node*));

错了。您正在使用 max+1 元素,但您只分配了一个元素。您必须分配 max+1 元素。

换句话说,该行应该是:

Bins = malloc(sizeof(struct Node*) * (max+1));

Bins = malloc(sizeof(*Bins) * (max+1));

另请注意,malloc() 族的转换结果为 considered as a bad practice

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?