【发布时间】:2016-01-24 17:07:14
【问题描述】:
我正在尝试使用递归来实现一种算法。 在递归中,我使用 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] = ...在数组外写入吗?由于它从low及以上开始计数,因此看起来有点可疑。
标签: c++ recursion memory-leaks