【问题标题】:Getting malloc assertion error in bin sort algorithm在 bin 排序算法中获取 malloc 断言错误
【发布时间】:2021-09-11 00:20:42
【问题描述】:

这是一个 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,5,3,2,6,4,11,5};
  BinSort(arr, n);
  printArray(arr, n);
  return 0;
}

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

【问题讨论】:

  • 你在做temp=(struct Node*)malloc(sizeof(struct Node)); temp=Bins[i]-&gt;next;,所以第二行是trashing你刚刚从malloc得到的指针。可能不是你想要的并且内存泄漏。
  • 没有断言。你怎么会得到一个断言错误?
  • 我认为他们有一个已在内部断言的调试分配器......但我确实希望他们粘贴了错误消息,而不是仅仅暗示它。跨度>
  • 缩进不好/有误导性。清理干净。

标签: c malloc free


【解决方案1】:

线

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() family 的转换结果是considered as a bad practice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-17
    • 2016-11-27
    • 2017-04-04
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多