简体   繁体   English

在C ++中删除动态分配的数组时出现令人困惑的错误

[英]Confusing error when deleting dynamically allocated array in C++

I am trying to implement a simple merge sort algorithm. 我正在尝试实现一个简单的合并排序算法。 What I am very confusing is that I keep getting the following error message right after the "array2" is deleted. 我非常困惑的是,删除“ array2”后,我一直收到以下错误消息。

" free(): invalid next size (fast) " “ free():下一个大小无效(快速)”

Please advise. 请指教。 Thank you very much! 非常感谢你!

#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;
}

The syntax 语法

new int(n+1)

Creates a single int on the free-store and initialises it with n+1 , and right away you access it out of bounds with array[1] . 在免费商店上创建一个int并使用n+1对其进行初始化,然后立即使用array[1]对其进行访问。 You want brackets: 您需要方括号:

new int[n + 1]

Which will create an array. 这将创建一个数组。 The same goes for every other place like that in the program. 程序中的其他所有地方也是如此。

Also, since you are starting your loop at 1 , the object array[0] is uninitialised and you get undefined behaviour if you access it, which you do. 另外,由于您从1开始循环,所以对象array[0]未初始化,如果访问它,您将得到未定义的行为。 This is wasting an array element for nothing and setting up traps for yourself, I recommend you don't add 1 to the array size and start your indices from 0. 这浪费了数组元素,没有为自己设置陷阱,我建议您不要在数组大小上加1并从0开始索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM