This is the mail archive of the glibc-linux@ricardo.ecn.wfu.edu mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: malloc problem/question in 2.1.3


On Mon, 5 Jun 2000, Kathy Bieltz wrote:

> Date: Mon, 05 Jun 2000 08:31:50 -0500
> From: Kathy Bieltz <kbieltz@hal-pc.org>
> Reply-To: glibc-linux@ricardo.ecn.wfu.edu
> To: glibc-linux@ricardo.ecn.wfu.edu
> Subject: Re: malloc problem/question in 2.1.3
> 
> Mike,
> 
> Do you do any XWindows programming???  One of the more
> common and hard to track down problems are SIGSEGV's
> caused by inadvertently freeing memory that was not previously
> allocated.

This simply means that you have bungled your logic for initializing and
destroying subsystems and objects.  This could be the result of poor planning
at the design stage.

> char* ptr = NULL ;
> 
> if (ptr != NULL) {
>    free(ptr) ;
>    ptr = NULL ;
> }

This is not necessary. Calling free on a null pointer is permitted by ANSI C.
Look it up in your library reference manual.  So you could just write:

    free(ptr);
    ptr = NULL;

> This makes sure you don't inadvertently free memory not previously
> allocated.

The problem with doing this solely for the purpose of trying to prevent bugs is
that it may incapacitate the effectiveness of tools that are designed to find
the problem, such as ElectricFence. By turning undefined behavior (calling free
on an indeterminate pointer) into well-defined behavior (calling free on a null
pointer) you may mask the bug, making it harder to pinpoint when the invalid
second call to free took place. You will have to work backwards from the
failed use of the null pointer to deduce out how it got that way.

> It's quite common to define pointers and then use malloc to
> allocate at runtime only the memory needed to display an image.
> If it's a photo display program, many different sized images may
> be displayed in one program and the same pointer to the image
> data would be free'd and re-allocated for each new image selected.

That's a special case; you have a short lived object, with a possible state of
``not present'' which needs to be indicated by a null value of the pointer, or
some other thing; the null value is necessary to the logic.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]