0

我正在尝试实现一个简单的合并排序算法。我非常困惑的是,在“array2”被删除后,我不断收到以下错误消息。

“ free(): 下一个尺寸无效(快速)”

请指教。非常感谢!

#include <iostream>
#include <limits.h>

using namespace std;

void merge_sort(int*,int,int);

int main(){
  //cout << "Max int: " << INT_MAX <<endl;
  int n;
  cin >> n;
  int* array = new int(n+1);
  for (int i=1; i<=n; i++)
    cin >> array[i];
  merge_sort(array,1,n);
  cout << "--------------------------------------------" <<endl;
  for (int i=1; i<=n; i++)
    cout << array[i] <<endl;
}

void merge_sort(int* array,int p,int r){
  cout << p << ' ' << r <<endl;
  if (p == r)
    return;
  int q = int((p+r)/2);
  merge_sort(array,p,q);
  merge_sort(array,q+1,r);
  //(p..q)  and (q+1 .. r) sorted, then merge this two sorted array
  int n1 = q-p+1;
  int n2 = r-q;
  cout << "Mark1 " <<n1<<' '<<n2<<endl;
  int *array1;
  array1 = new int(n1+1);
  int *array2;
  array2 = new int(n2+1);
  for (int i=p; i<=q; i++)
    array1[i-p] = array[i];
  for (int i=q+1; i<=r; i++)
    array2[i-q-1] = array[i];
  array1[n1] = INT_MAX;
  array2[n2] = INT_MAX;  //CONSTANT, serve as sentinel

  int p1 = 0;
  int p2 = 0;
  cout << "Mark2" << endl;
  for (int i=p; i<=r; i++){
    if (array1[p1]<array2[p2]){
      array[i] = array1[p1];
      p1++;
    }else{
      array[i] = array2[p2];
      p2++;`enter code here`
    }
  }   
  cout << "Mark3" << endl;
  delete [] array2;
  cout << "Delete array2 " << endl;

  delete [] array1;
  cout << "Delete array1 " << endl;
}
4

1 回答 1

1

语法

new int(n+1)

int在 free-store 上创建一个单曲并用 初始化它n+1,然后你马上用 . 越界访问它array[1]。你想要括号:

new int[n + 1]

这将创建一个数组。程序中的每个其他地方也是如此。

此外,由于您在 开始循环1,因此该对象array[0]未初始化,如果您访问它,您将获得未定义的行为,您会这样做。这是白白浪费一个数组元素并为自己设置陷阱,我建议您不要将数组大小加 1 并从 0 开始索引。

于 2013-01-25T03:25:50.870 回答