Wang WolfLouis
7/6/2011 1:50:00 AM
On 7?5?, ??11?29?, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
> On 7/5/2011 11:09 AM, Wang WolfLouis wrote:
>
> > [...]
> > void pkt_obj_free(pkt_obj_st **pp)
> > {
> > pkt_obj_st *obj;
> > obj = *pp;
> > [...]
> > free(*pp);
> > *pp = NULL;
> > }
> > [...]
> > if I change *pp = NULL in
> > void pkt_obj_free(pkt_obj_st **pp) function to obj = NULL, then
> > the pkt_objs pointer array didn't remove pkt_objs[2] pointer. I don't
> > know why? can anybody explain the reason?
>
> `obj' is a variable local to pkt_obj_free, a variable whose
> value is copied from `*pp'. If you copy a value and then change
> the copy, you have not affected the original.
>
> By the way, your code has other problems, too. One of those
> is the use of a memory block that has already been free'd: When
> you store `obj01' in all five positions of `ptr_obj[]', you are
> not thereby creating five separate memory areas. Rather, you
> are making five copies of a pointer to one malloc'ed memory area.
> When you free that memory area, all five pointers (six, counting
> the `obj01' original) become unusable. You set one of the five
> to NULL, but the other four are still pointing to the vanished
> memory -- yet the pkt_obj_print function will try to use them
> anyhow, with unpredictable consequences. The commented-out
> call to `free(obj01)' would also be Trouble with a capital T,
> because the memory `obj01' points to has already been free'd.
>
> --
> Eric Sosman
> esos...@ieee-dot-org.invalid
Thnaks, Is obj is just a pointer copy of *pp? In other words, obj is
only a copy memeory
address of *pp, so obj->pkt->data can free the memory alloc by pkt01-
>data = (char*)malloc(sizeof(char)*100);
I want to free the pkt_objs pointer array refered to elements, for
example,
free pkt_objs[2] and set pkt_objs[2] = NULL. Then
for (i = 0; i < 5; i++) {
if (pkt_objs[i])
can known this array element have been freed. pkt_objs[2] can be
pointed to new alloced
pkt_obj_st pointer.
}
I only find the code as follows that could do the job:
void pkt_obj_free(pkt_obj_st **pp)
{
pkt_obj_st *obj;
obj = *pp;
if (obj->pkt) {
free(obj->pkt->data);
free(obj->pkt);
obj->pkt = NULL;
}
free(*pp);
*pp = NULL;
}
But it is ungly, have any other method do the job?