开发者

problem with free function again!!!(C linux)

开发者 https://www.devze.com 2023-03-26 01:16 出处:网络
I have a problem with free() function in C linux. here is my sample code: typedef struct { char index[2];

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 don't have enough code posted, but IMO, you said that ps and _ps are global, so once you free _ps there might be a chance it's being used somewhere else in your program, causing it to crash. I'd suggest you go over the program and see where _ps is used, or supply us with more code.

Hope this helps.


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..???


A crash at free() means probably that either:

  1. You already freed this memory,
  2. The allocated memory was corrupted - check if you overridden some of the memory.
  3. The pointer you try to free, is not the pointer returned from malloc / calloc - check if you changed _ps value somewhere.
0

精彩评论

暂无评论...
验证码 换一张
取 消