gpt4 book ai didi

c++ - 为什么在动态分配的数组上调用 delete 会导致一个崩溃而不是另一个?

转载 作者:行者123 更新时间:2023-11-28 01:39:14 25 4
gpt4 key购买 nike

我正在开发一个可以进行合并排序的函数。我有一个有效的合并功能,但我的拆分功能有一些问题。 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) 方法的第一个循环中(将元素复制到左侧数组中)

关于c++ - 为什么在动态分配的数组上调用 delete 会导致一个崩溃而不是另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com