我想知道確定下面的代碼是否會產生內存泄漏的最好方法,因爲我知道在使用完內存時必須釋放內存,但同時這個數組或指針指向的是當函數返回時超出範圍,那麼我是否釋放它並不重要?這段代碼是生成內存泄漏還是乾淨?
但是,在這種特殊情況下,我不能在不中斷堆ATLEAST根據在Visual Studio 2010
微軟調試器,並學習如何最好地處理這個請你描述檢查內存的方式釋放內存泄漏。
在此先感謝
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int sieve(int n)
{
int *a = (int *) malloc(sizeof(int) * n);
int max = floor(sqrt((double)n));
int p = 2;
memset(a,0,sizeof(int) * n);
while(p<=max)
{
for(int i = 2 * p; i <= n; i+= p)
a[i] = 1;
while(a[++p]) /* Empty */ ;
}
while(a[n]) n--;
/* free(a); */ // free our array as we are done with it. but it generate a heap error
return n;
}
int main(void)
{
cout << sieve(100) << endl;
system("pause");
return 0;
}
你有越界訪問,因此可能是你釋放錯誤 – Anycorn 2012-03-05 11:17:18
沒有時間去調試這個給你,但Valgrind的說,有一個內存讀/寫錯誤 – kfmfe04 2012-03-05 11:18:21
你可能想看看'alloca' - HTTP:/ /www.mkssoftware.com/docs/man3/alloca.3.asp – sje397 2012-03-05 11:20:26