I have a code like below. Here, I have a structure "chair" with a member A and from main, am calling a fucntion "func1" for a number of iterations. Inside func1, I have an integer typeA allocated with 10000 addresses and assigned values. Now, allocated 100 chairs of struct chair. I want each chair to hold 100 distinct addresses of typeA. For example, chair[0] = 0-99 of typeA, chair[1]= 1-199 of type B and so on. Then i use each such chair for parallel processing. Anyhow, am not showing the parallel code here. My problem is, after finishing i am trying to free the memory. But somewhere am getting a memory leakage which extremely slows down my program after few iterations. How to re-implement this code without this leakge problem. Thank u.
struct chair
{
int *A;
};
typedefstruct chair chair;
int main()
{
for(unsignedint i=0;i<100;i++)
{
func1();
}
return 0;
}
void func1()
{
int *typeA;
typeA = (int*)malloc(sizeof(int) * 10000);
for(unsignedint i=0;i<10000;i++)
{
typeA[i]=i;
}
chair * ch;
// now i define 100 chairs of type chair
ch = (chair*)malloc(sizeof(chair) * 100);
int count =0;
// now i allocare 100 addreess from typeA for each chair (i.e.), ch[0] = 0-99 from typeA, ch[1] = 1-199 from typeA and so on
for(unsignedint i=0;i<100;i++)
{
ch[i].A = typeA + count;
count = count + 100;
}
/// Now i parallely process each chair/// am not showing parallel processing
//after parallel processing is over, am doing this...
free(typeA);
free(ch);
//But i get a memory leak in the above for loop so my program is running slolwy after some iterations
}
#include <stdlib.h> /* malloc, free, rand */
constint MAX = 100;
typedefstruct
{
int *ptr;
}chair;
void func1()
{
//MAX
chair ary[MAX];
//Array of MAX pointers point to
for (unsignedint i = 0; i < MAX; i++)
ary[i].ptr = (int*)malloc(sizeof(int)* 100);
//Deallocate
for (unsignedint i = 0; i < MAX; i++)
free(ary[i].ptr);
}
int main()
{
func1();
return 0;
}
Thanks for the reply. Do i need to do the second for loop (Allocation) before the are where i do ch[i].A = typeA + count???,, if that still memory overflow doesn happen??
Your original code is a little unorthodox but it looks okay. Perhaps your parallel processing function is corrupting memory. If you run the program as you've shown it does memory leak?
The way to handle memory leak issues is to figure out who "owns" the memory. That boils down to who has responsibility for deleting it. YOu can also simplify things by using constructors and destructors. For example, in this case maybe every chair has an array of 100 ints. If that's true then allocate the array in the chair constructor and delete it in the destructor.