I have a struct as follows:
typedef struct somefruits{
struct pine abc;
int xyz;
}pm;
struct pine
{
unsigned char *ch;
unsigned char *data;
unsigned int a;
}
int function(unsigned int nfruits, pm **outfruits)
{
pm *fruits = NULL;
status = 0;
void *tmp = NULL;
tmp = realloc(fruits, (nfruits + 1) * sizeof *fruits);
if (tmp != NULL)
fruits = tmp;
//do some manipulations on fruits. malloc and assign values for ch and data;
for (i =0 ;i<nfruits;i++)
{
// do some stuff
fruits[i]->abc.data = malloc(20);
//write some stuff into data
fruits[i]->abc.ch = malloc(100);
//write some stuff into ch
}
//do manipulations which can result in change of status variable
*outfruits = fruits;
return status;
}
int main ()
{
pm *Fmain;
function(10, &Fmain);
// do some stuff with Fmain
dispose(Fmain, 10);
}
dispose(pm *object, int n)
{
for(i=0;i<n;i++)
{
free((object+i)->abc.ch);
free ((object+i)->abc.data);
}
free (object);
}
When I run valgrind on the following code I get
HEAP SUMMARY:
==4699== 421 (352 direct, 69 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 4
==4699== by 0x4A079DA: realloc
==4699== by 0x40A065: function (file1.c:623)
Line 623 points to tmp = realloc(fruits, (nfruits + 1) * sizeof *fruits)
line
Since I am freeing the memory in dispose I am unable to understand what it is that I am doing wrong. Any help will be much appreciated.