为什么在动态分配的数组上调用 delete 会导致一个崩溃而不是另一个?
Why does calling delete on a dynamically allocated array cause one to crash but not the other?
我正在开发一个可以进行合并排序的函数。我有一个有效的合并功能,但我的拆分功能有一些问题。函数 split
采用单个 int 数组及其大小,然后将该数组拆分为两个较小的数组。我的问题是,我不知道为什么在 tempArrayL
上调用 delete []
会导致崩溃,但是当我在 tempArrayR
上调用时却不会。
void split(int x[], int size)
{
if (size == 1)
return;
//figure out sizes of smaller arrays
int leftSize = (size / 2), rightSize = (size - leftSize), mid = (leftSize + 1);
int* tempArrayL = new int[leftSize]; //array for first half
for (int z = 0; z != mid; z++)
{
tempArrayL[z] = x[z]; //copy from original into new array
}
for (int z = 0; z != leftSize; z++)
cout << tempArrayL[z] << endl; //print out to see if it worked
int* tempArrayR = new int[rightSize]; //array for second half
for (int z = mid - 1, j = 0; z != size; j++, z++)
{
tempArrayR[j] = x[z]; //copy from original array
}
for (int z = 0; z != rightSize; z++)
cout << tempArrayR[z] << endl; //print out to see if it worked
delete [] tempArrayL; //causes crash here
delete [] tempArrayR; //does not cause crash if I comment out tempArrayL
}
下面是它在 main
中的使用方式
int main()
{
const int SIZE = 5;
int array[] = {3, 2, 5, 9, 10};
split(array, SIZE);
}
基本上就像@Bo Persson 在他的评论中提到的那样。您正在访问超出范围的元素。
您的 tempArrayL
分配了 2 个元素的大小(意味着只有索引 {0,1})
但是在第一个循环中(你将元素复制到左数组中),你的循环条件是 z!=mid
而你的 mid
是 3 这意味着你正在访问索引 {0,1,2} 和你的tempArrayL
只能有索引 {0,1}。因此,索引越界。
长话短说:
替换for (int z = 0; z != mid; z++)
有for (int z = 0; z !=leftSize; z++)
在 split(int[] x,int size)
方法的第一个循环中(将元素复制到左侧数组中)
我正在开发一个可以进行合并排序的函数。我有一个有效的合并功能,但我的拆分功能有一些问题。函数 split
采用单个 int 数组及其大小,然后将该数组拆分为两个较小的数组。我的问题是,我不知道为什么在 tempArrayL
上调用 delete []
会导致崩溃,但是当我在 tempArrayR
上调用时却不会。
void split(int x[], int size)
{
if (size == 1)
return;
//figure out sizes of smaller arrays
int leftSize = (size / 2), rightSize = (size - leftSize), mid = (leftSize + 1);
int* tempArrayL = new int[leftSize]; //array for first half
for (int z = 0; z != mid; z++)
{
tempArrayL[z] = x[z]; //copy from original into new array
}
for (int z = 0; z != leftSize; z++)
cout << tempArrayL[z] << endl; //print out to see if it worked
int* tempArrayR = new int[rightSize]; //array for second half
for (int z = mid - 1, j = 0; z != size; j++, z++)
{
tempArrayR[j] = x[z]; //copy from original array
}
for (int z = 0; z != rightSize; z++)
cout << tempArrayR[z] << endl; //print out to see if it worked
delete [] tempArrayL; //causes crash here
delete [] tempArrayR; //does not cause crash if I comment out tempArrayL
}
下面是它在 main
中的使用方式int main()
{
const int SIZE = 5;
int array[] = {3, 2, 5, 9, 10};
split(array, SIZE);
}
基本上就像@Bo Persson 在他的评论中提到的那样。您正在访问超出范围的元素。
您的 tempArrayL
分配了 2 个元素的大小(意味着只有索引 {0,1})
但是在第一个循环中(你将元素复制到左数组中),你的循环条件是 z!=mid
而你的 mid
是 3 这意味着你正在访问索引 {0,1,2} 和你的tempArrayL
只能有索引 {0,1}。因此,索引越界。
长话短说:
替换for (int z = 0; z != mid; z++)
有for (int z = 0; z !=leftSize; z++)
在 split(int[] x,int size)
方法的第一个循环中(将元素复制到左侧数组中)