Complete.Org: Mailing Lists: Archives: freeciv-dev: March 2002:
[Freeciv-Dev] Re: newbie C question
Home

[Freeciv-Dev] Re: newbie C question

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: "Per I. Mathisen" <Per.Inge.Mathisen@xxxxxxxxxxx>
Cc: freeciv-dev@xxxxxxxxxxx
Subject: [Freeciv-Dev] Re: newbie C question
From: Ben Webb <ben@xxxxxxxxxxxxxxxxxxxxxx>
Date: Tue, 5 Mar 2002 12:02:47 +0000 (GMT)

On Tue, 5 Mar 2002, Per I. Mathisen wrote:

> Will pointers always be initialized to NULL?

No. No variables are initialised at all in C.

> I seem to remember reading that somewhere, but maybe that wasn't
> about C :)

        Some languages do (e.g. Perl, and some implementations of 
Fortran). But not C.

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

        Unsafe, because ptr is uninitialised. (The check is pointless 
anyway, because free(NULL) should be a no-op.)

> char *ptr;
> fc_realloc(ptr, 4096);

ptr = fc_realloc(ptr, 4096); But nope.

> struct mystruct *ptr;
> fc_malloc(ptr, 11 * sizeof(&ptr));
> if (ptr[0]->ptr!=NULL) free(ptr[0]->ptr);

        I think you mean ptr = fc_malloc(11 * sizeof(struct mystruct)); 
But still nope. ;)

> If not, how about this:
> 
> struct mystruct *ptr;
> fc_calloc(ptr, 11 * sizeof(&ptr));
> if (ptr[0]->ptr!=NULL) free(ptr[0]->ptr);

ptr = fc_calloc(11, sizeof(struct mystruct));
if (ptr[0].ptr != NULL) free(ptr[0].ptr);

        Assuming struct mystruct has a "ptr" member, that should work, 
since calloc zeroes the memory.

        Ben
-- 
ben@xxxxxxxxxxxxxxxxxxxxxx           http://bellatrix.pcl.ox.ac.uk/~ben/
"Jeeves shimmered out and came back with a telegram."
        - 'Jeeves Takes Charge', P. G. Wodehouse



[Prev in Thread] Current Thread [Next in Thread]