我正在尝试使用递归来实现算法。 在递归中我使用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;
}
答案 0 :(得分:0)
编译代码并在valgrind
中运行它会导致内存泄漏的第一次出现:
==20797== Invalid write of size 4
==20797== at 0x400BA0: Sort_And_count_split_Inv(int*, int, int, int) (in /home/test/TestCPP)
==20797== by 0x4009D4: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x4009BC: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x4009A2: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x400921: main (in /home/test/TestCPP)
==20797== Address 0x5a1d0ec is 4 bytes after a block of size 8 alloc'd
==20797== at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==20797== by 0x400AE8: Sort_And_count_split_Inv(int*, int, int, int) (in /home/test/TestCPP)
==20797== by 0x4009D4: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x4009BC: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x4009A2: Sort_And_count(int*, int, int) (in /home/test/TestCPP)
==20797== by 0x400921: main (in /home/test/TestCPP)
我把它钉在了这一行:
tmp[k] = a[i];
这意味着k
的数量大于分配的int[]
数组的长度。由于您分配了high - low + 1
和k = low
的长度,因此超越了边界案例2*low = high + 1
。
我没有详细介绍您的实际排序算法以及为什么您正在以错误的low
(或high
)进食,但是这是你的内存泄漏的来源。