[Discuss] Casting the return value of malloc bad?

Noel Burton-Krahn noel at burton-krahn.com
Sat Jul 15 23:32:23 PDT 2006


Without pomposity, here's what works for me:

int err = -1;
MyType *p = 0;

do {
    /* allocate memory and use a debug library to detect leaks */
    p = malloc(sizeof(*p));
    debug_leak_create_assertb(p);

    /* do some more actions with error checking */

    err = 0;
} while(0);

/* clean up on error */
if( err ) {

    debug_leak_free(p);
    free(p);
}

(1) I like the "do { /* lots of error checking */ err=0; } while(0);" 
construct because it avoids a lot of nested if's like "if(malloc) { if(open) 
{} if(read) { } else {} else {} else {}, etc."  I find nested if/else blocks 
really hard to read, and the cleanup-on-error code gets really scattered.

(2) I have a debug library that defines macros to track allocated resource 
by the source file and line number they were allocated at.

#define debug_leak_create_assertb(x) \
    if( !(x) ) { /* error message about x */; break; }
    debug_leak_record((x), __FILE__, __LINE__)

#define debug_leak_free(x) \
    if( (x) )  { debug_leak_forget((x)); (x) = 0; }

During debugging, I periodically log the total number of allocations by line 
number.  If there's a leak, the allocations at one particular line will 
constantly increase, so it's easy to find out what's leaking and where it 
starts.  My library also complains when something is freed twice.


--Noel



----- Original Message ----- 
From: "Paul Nienaber" <phox at phox.ca>
To: <discuss at vlug.org>
Sent: Saturday, July 15, 2006 7:01 PM
Subject: Re: [Discuss] Casting the return value of malloc bad?


> Writing good (AND easy to maintain AND elegant) code that happens to use
> dynamic memory allocation isn't exactly as "simple" as you may like to
> make it seem.  If in doubt, post some of your C code.  I'll be glad to
> show you what you, too, did wrong.
>
> ~p
>
> Owen Stampflee wrote:
>> If you need a helper library to do simple stuff like malloc, please step
>> away from the keyboard and don't program in C, there is already enough
>> exploit ridden code out there, we don't need more of it.
>>
>> _______________________________________________
>> Discuss mailing list
>> Discuss at vlug.org
>> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss
>>
>>
>
> _______________________________________________
> Discuss mailing list
> Discuss at vlug.org
> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss
> 



More information about the Discuss mailing list