[Freeciv-Dev] Re: newbie C question
[Top] [All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
On Tue, Mar 05, 2002 at 12:46:29PM +0100, Per I. Mathisen wrote:
> Will pointers always be initialized to NULL?
[#10] If an object that has automatic storage duration is
not initialized explicitly, its value is indeterminate. If
an object that has static storage duration is not
initialized explicitly, then:
- if it has pointer type, it is initialized to a null
pointer;
- if it has arithmetic type, it is initialized to zero;
- if it is an aggregate, every member is initialized
(recursively) according to these rules;
- if it is a union, the first named member is initialized
(recursively) according to these rules.
Translated: value of local variables are undefined. If the keyword
static is on front of the variable it is NULL.
> I seem to remember reading
> that somewhere, but maybe that wasn't about C :)
>
> In other words, are these safe:
> char *ptr;
> if (ptr!=NULL) free(ptr);
Unsafe. I'm pretty sure the compiler will give a warning on this.
> char *ptr;
> fc_realloc(ptr, 4096);
Unsafe.
> struct mystruct *ptr;
> fc_malloc(ptr, 11 * sizeof(&ptr));
> if (ptr[0]->ptr!=NULL) free(ptr[0]->ptr);
[#2] The malloc function allocates space for an object whose
size is specified by size and whose value is indeterminate.
So unsafe.
> If not, how about this:
>
> struct mystruct *ptr;
> fc_calloc(ptr, 11 * sizeof(&ptr));
> if (ptr[0]->ptr!=NULL) free(ptr[0]->ptr);
[#2] The calloc function allocates space for an array of
nmemb objects, each of whose size is size. The space is
initialized to all bits zero.225
__________
225. Note that this need not be the same as the
representation of floating-point zero or a null pointer
constant.
So safe on common platforms and may break on exotic ones.
Raimar
--
email: rf13@xxxxxxxxxxxxxxxxx
"The primary purpose of the DATA statement is to give names to
constants; instead of referring to pi as 3.141592653589793 at every
appearance, the variable PI can be given that value with a DATA
statement and used instead of the longer form of the constant. This
also simplifies modifying the program, should the value of pi
change."
-- FORTRAN manual for Xerox Computers
- [Freeciv-Dev] Re: newbie C question, (continued)
[Freeciv-Dev] Re: newbie C question, Jules Bean, 2002/03/05
[Freeciv-Dev] Re: newbie C question, Piotr Sulecki, 2002/03/05
[Freeciv-Dev] Re: newbie C question, Reinier Post, 2002/03/06
[Freeciv-Dev] Re: newbie C question,
Raimar Falke <=
|
|