void mergeSort(int* nums, int begin, int end) { if (begin >= end) { return; } int len = end - begin+1; int mid = begin + (end - begin) / 2; mergeSort(nums, begin, mid); mergeSort(nums, mid+1, end); int* temp = new int[len]; temp = { 0 }; int l1 = begin, r1 = mid; int l2 = mid+1, r2 = end; int i = begin; for (; l1 <= r1 && l2 <= r2;) { if (nums[l1] < nums[l2]) { temp[i++] = nums[l1++]; } else { temp[i++] = nums[l2++]; } } for (; l1 <= r1;) { temp[i++] = nums[l1++]; } for (; l2 <= r2;) { temp[i++] = nums[l2++]; } for (int j = 0; j < len; j++) { nums[j+begin] = temp[j]; } } 出现读取访问冲突,修改代码
时间: 2024-01-22 18:01:45 浏览: 56
在代码中,`temp`被赋值为一个新的`int`数组,然后又被赋值为`{0}`,这样会导致`temp`指向了一个新的内存地址,原有的内存地址被泄漏。在后续的代码中,程序又对这个新的内存地址进行了读写操作,从而导致了读取访问冲突。为了解决这个问题,应该在申请`int`数组的同时,将数组中的元素全部初始化为0。修改后的代码如下:
```
void mergeSort(int* nums, int begin, int end) {
if (begin >= end) {
return;
}
int len = end - begin+1;
int mid = begin + (end - begin) / 2;
mergeSort(nums, begin, mid);
mergeSort(nums, mid+1, end);
int* temp = new int[len](); // 将数组中的元素全部初始化为0
int l1 = begin, r1 = mid;
int l2 = mid+1, r2 = end;
int i = begin;
for (; l1 <= r1 && l2 <= r2;) {
if (nums[l1] < nums[l2]) {
temp[i++] = nums[l1++];
}
else {
temp[i++] = nums[l2++];
}
}
for (; l1 <= r1;) { temp[i++] = nums[l1++]; }
for (; l2 <= r2;) { temp[i++] = nums[l2++]; }
for (int j = 0; j < len; j++) {
nums[j+begin] = temp[j];
}
delete[] temp; // 释放动态申请的内存空间
}
```
阅读全文