I would like to know the best way to determine if the following code is generating memory leaks, as I understand that you have to free the memory when you are done using it, but in the same time this array or pointer to int is out of scope when the function return then it does not matter if I release it or not?
But in this particular case I cannot release the memory without interrupting the heap atleast according to microsoft debugger in Visual studio 2010.
And for learning how to best approach this could you please describe your ways of checking for memory leaks.
Thanks in advance
#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;
}
there are memory leaks in your program as you are not freeing the memory allocated.
use “free” here as you have used malloc and incase if you plan on using “new” then use “delete” operator
try to free memory before return statement.
you can also use the valgrind tool to find out the memory leaks in your program
check this url for more information.
this tool will help you to find out memory leaks in your programme.