[Freeciv-Dev] Re: newbie C question
[Top] [All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
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
|
|