dimanche 29 mars 2015

C/C++ dynamic memory allocation using realloc() and free()


In the code below, I have made a function for finding the prime numbers between two given number. What I am trying to do is, from the given list of initial numbers remove all the numbers divisible by the first prime number, i.e. 2, then from the new list of the remaining elements, remove those divisible by 3, and continue so on till number<=square root(maximum given number).


How I have implemented this is create a pointer of integers storing the initial list. Check for divisibility and store the indivisible elements in a new pointer of integers. Once that is done, I want to free the initial pointer, in my case "inp_storage", reallocate it memory of the size of the second list, which is "storage", and make it point to what "storage points to". Then I want to free "storage" so that it can store a new list, maybe of different size.


x,y are the given two numbers between which I have to find the prime numbers.


However, on building and debugging in visual studio 10, I get this error during runtime:


HEAP[primenumgen.exe]: Invalid address specified to RtlValidateHeap( 007E0000, 007E57B4 ) Windows has triggered a breakpoint in primenumgen.exe.


This may be due to a corruption of the heap, which indicates a bug in primenumgen.exe or any of the DLLs it has loaded.



int num_begin=2, num_n=x;

int storage_count =0;

float sqrt_num=sqrt(float(y));

int *inp_storage=(int*)malloc(sizeof(int)*(y-x));

int *storage=(int*)malloc(sizeof(int)*(y-x));

int *inp_head=inp_storage;
int *storage_head=storage;

for(int i=x; i<=y; i++)
{
*inp_storage=i;
inp_storage++;
}
inp_storage=inp_head;

while(num_begin<=(int)sqrt_num)
{
storage_count=0;
while(*inp_storage >0)//!=NULL)
{
if(*inp_storage%num_begin >=1)
{
cout<<"Inside if "<<*inp_storage<<"\n";

*storage=*inp_storage;
storage++;
storage_count++;
}
inp_storage++;
}
free(inp_storage);
inp_storage=(int *)realloc(inp_storage, sizeof(int)*storage_count);
storage=storage_head;
inp_storage=storage;

if(num_begin==2)
{
num_begin=num_begin+1;
}
else
{
num_begin=next_num_gen();
cout<<"next number is "<<num_begin <<"\n";
}
}



Aucun commentaire:

Enregistrer un commentaire