Mail Archives: djgpp/1997/01/09/00:46:46
Christoph Kukulies wrote:
>
> > Hi,
> >
> > Just a small question about free() function
> >
> > Let's :
> >
> > char *ptr1,*ptr2;
> >
> > ptr1=(char*)malloc(sizeof(char)*1024);
> > if (ptr1!=NULL) ptr2=ptr1;
> > ....
> >
> > //so my question. May i use
> > free(ptr2);
>
> Yes, you may use ptr2 as well. It's the address that corresponds to
> the malloc that's freed, not the pointer.
> But beware, in the example given you should only free(ptr1)
> or free(ptr2) if ptr1 or ptr2 have been initialized
> to some senseful value.
>
> In the above code portion ptr2 doesn't get initialized and if
> the malloc returned a 0 for some reason you would invoke
> free() later with a wild pointer.
>
> > //or i have to use
> > free(ptr1)
> >
> > --
> > Regards,
> > Dim Zegebart,
> > Moscow Russia.
> >
>
> --Chris Christoph P. U. Kukulies kuku AT gil DOT physik DOT rwth-aachen DOT de
Good habits are as hard to break as bad ones. I always check the
return from malloc (or fopen) in a conditional like:
if ((ptr1 = (char *)malloc(1024)) == NULL)
do_not_pass_go();
ptr2 = ptr1;
There is little you can do if malloc() fails and there is no use
continuing with the program. Make it stop and try to fix it.
In any case, if malloc() fails, neither ptr1 nor ptr2 contain valid
pointers. And there is nothing to free() anyway.
--
Joe Wright mailto:wrightj AT exis DOT net
"Everything should be made as simple as possible, but not simpler."
--Albert Einstein--
- Raw text -