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: Raimar Falke <hawk@xxxxxxxxxxxxxxxxxxxxxxx>
Date: Tue, 5 Mar 2002 13:14:05 +0100
Reply-to: rf13@xxxxxxxxxxxxxxxxxxxxxx

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


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