Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 18 Dec 2000 11:08:25 -0800 (PST)
From:      Matt Dillon <dillon@earth.backplane.com>
To:        Jack Rusher <jar@integratus.com>
Cc:        "Jacques A. Vidrine" <n@nectar.com>, Warner Losh <imp@village.org>, hackers@FreeBSD.ORG
Subject:   Re: Why not another style thread? (was Re: cvs commit: src/lib/libc/gen ..
Message-ID:  <200012181908.eBIJ8PP46165@earth.backplane.com>

next in thread | raw e-mail | index | archive | help
:  I find that I still use the:
:
:    if( foo )
:        free( foo );
:
:...syntax a large part of the time.  It's a habit developed before you
:could trust the free() implementation on every platform to conform to
:sanity.  It also prevents me from getting into the habit of using syntax
:that will get me into trouble when programming in embedded environments
:& kernels.  In any case, this style doesn't raise the "what the hell?"
:flag the way a number of other things do.
:
:Jack

    I go one step further and have a routine which NULLs out the 
    pointer variable itself.

    routine()
    {
	...
	safe_free(&ptr);
	...
    }

    void
    safe_free(void **ptr)
    {
	if (*ptr) {
	    free(*ptr);
	    *ptr = NULL;
	}
    }

    And for malloc, so I don't have to check the return value
    in the hundreds of places I call it:

    void *
    safe_malloc(int bytes) 
    {
	void *ptr;

	if ((ptr = malloc(bytes)) == NULL)
	    *(int *)0 = 1;	/* force seg fault */
	return(ptr);
    }

    And for asprintf(), same deal.  It isn't much use if you call it
    a billion times and have to check the return value every time.

    int
    safe_asprintf(char **pptr, const char *ctl, ...)
    {
	va_list va;
	int r;

	va_start(va, ctl);
	r = vasprintf(pptr, ctl, va);
	va_end(va);
	if (r < 0)
	    *(int *)0 = 1;	/* force seg fault */
	return(r);
    }


						-Matt



To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200012181908.eBIJ8PP46165>