我想實現一個算法,使用遞歸。 在遞歸中,我使用new分配內存並將其刪除,但仍然出現內存泄漏。我試圖瞭解我做錯了什麼,但無法弄清楚。 有人可以看看嗎?遞歸內存泄漏
- 我知道我可以使用矢量,但想了解我做錯了什麼,以及如何解決它。
這是代碼:
#include <iostream>
#include <fstream>
#include <math.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
int sortInv(int*,int);
int Sort_And_count_split_Inv(int*,int,int,int);
int Sort_And_count(int *,int,int);
int main()
{
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int Siz = 9;
int Arr[9] = {66,3,11,76,93,9,22,56,89};
int b = Sort_And_count(Arr,0,Siz-1);
for (int i=0; i<Siz; i++)
Arr[i] = Arr[i];
return 0;
}
int Sort_And_count(int *a,int low,int high)
{
int mid;
int n = 0;
if (low >= high)
return 0;
else
mid = (high+low)/2;
n+= Sort_And_count(a,low, mid);
n+= Sort_And_count(a, mid+1, high);
n+= Sort_And_count_split_Inv(a,low,mid,high);
return n;
}
int Sort_And_count_split_Inv(int* a, int low, int mid, int high)
{
int i,j,k;
i=low;
j=mid+1;
k=low;
int count = 0;
int* tmp = new int[high-low+1];
while (i<=mid && j<=high)
{
if (a[i]<a[j])
{
tmp[k] = a[i];
i++;
}
else
{
tmp[k] = a[j];
j++;
count += mid-i == 0? 1: mid+1-i;
}
k++;
}
while (i<=mid)
tmp[k++] = a[i++];
while (j<=high)
tmp[k++] = a[j++];
for (i=low; i<=high; i++)
a[i] = tmp[i];
delete[] tmp;
_CrtDumpMemoryLeaks;
return count;
}
你確定'k'永遠不會超過'high-low'並且'tmp [k] = ...'在陣列之外寫入嗎?由於它從低位開始向上計數,看起來有點可疑。 –