This is the edited code:
I have a two dimensional stack, like
#define push(s,ele) s.list[++(s.last)]=ele
typedef struct vp {
short int v1,v2;
}VPTYPE;
typedef struct VPLIST{
int last;
VPPTR *list;
}VPLISTTYPE,*VPLISTPTR ;
VPLISTPTR v1v2;
v1v2=(VPLISTPTR)malloc(sizeof(VPLISTTYPE)*nof);
a=0;
while(a<100)
{ //allocation part
for(i=0;i< nof;i++)
{
v1v2[i].list=(VPPTR *)malloc(20*(sizeof(VPPTR)));
for(i2=0;i2< 10;i2++) //please note that I am not filling the array completely, in the actual code the value 10 is dependent on certain factors, which I am omitting for the sake of simplicty
{
v=(VPTYPE *)malloc(sizeof(VPTYPE));
push(v1v2[i],v);
v1v2[i]->v1=1;v1v2[i]->v2=2;
}
}
// some algorithm goes on here which accesses these values in the stack
// free memory part
for(i=0;i< nof;i++)
{
for(i2=0;i2<= (v1v2[i2].last);i2++)
{
free(v1v2[i2].list[i]);
}
}
a++;
}
When I free the memory this way there is memory leakage. Please let me know where I am going wrong.
Thank you very much.
You are not initializing the allocated memory in the code you show. In general, you get non-zero garbage allocated by
malloc(). If you need zeroed memory, usecalloc().There’s also the problem identified by JCooper‘s answer.
There’s also the problem identified by Muggen‘s comment.
You are freeing the items on the stack, but not the stacks as a whole. That should be done inside the ‘
for (i2 = 0; ...)‘ loop but after the ‘for (k2 = 0; ...)‘ loop.Collectively, these add up to a minor catastrophe.
After the code edit…
typedef VPTYPE *VPPTR;.In your free memory loop, in the call to
free(), you have reversed the roles ofiandi2:v1v2[i]->v1=1;v1v2[i]->v2=2;) are bogus.The following code compiles clean and runs clean:
Working Code
Simpler Working Code
This code uses one less level of indirection – and one less level of memory allocation, therefore – and compiles and runs equally cleanly.