I have a problem with free() function in C linux. here is my sample code:
typedef struct
{
char index[2];
char color[2];
char duration[2];
} ps;
ps *_ps = NULL;
I need to allocate and free the above structure repeatedly using the following function:
ps * readMatrix(mmc_item_item_screen *_item_screen,int rows,int skip)
{
if(_ps)
{
free(_ps);
_ps=(ps *)NULL;
}
_ps=(ps *)calloc(rows-1,sizeof(ps));
memset(_ps,'\0',((rows-1)*sizeof(ps)));
int i=0;
for(i=0;i<rows;i++)
{
if((i+1)>=skip)
{
sprintf(_ps[i].index,"%d",i);
sprintf(_ps[i].color,"%s",getCDKMatrixCell(_item_screen->matrix,i+2,1));
sprintf(_ps[i].duration,"%s",getCDKMatrixCell(_item_screen->matrix,i+2,2));
}
else
{
sprintf(_ps[i].index,"%d",i);
sprintf(_ps[i].color,"%s",getCDKMatrixCell(_item_screen->matrix,i+1,1));
sprintf(_ps[i].duration,"%s",getCDKMatrixCell(_item_screen->matrix,i+1,2));
}
}
return _ps;
}
main()
{
while(1)
....
_ps=readMatrix(_item_screen,rows,getCDKMatrixRow(_item_screen->matrix));
....
}
First time that I call the above function, _ps is NULL so free() is not invoked. but the second time(_ps already allocated), program crashes as soon as free() is called.
Can you help me with this?
(ps and _ps are both global)
Thank you.
Edit1 I put the whole function that manipulates _ps. and this is the only function working on _ps. could you help pllease?
YOU ARE allocating rows-1 elements but accessing rows elements in your loop..
so me because of that…
one more thing if your _ps is global then why you are returning that..???