Re: Is this OK?



it is very typical for poeple to do:

if ((ptr = malloc(size)) == NULL) {
        /* error code */
} else {
        memset(ptr, 0x00, size);
}

other than file descriptors which you need at "-1"
usually "0" is uninitialized. (this all depends on
what you just allocated).

but the above peice of code is pretty frequent.
this can be replaced by:

ptr = g_malloc0(size);

If "g_malloc0" fails it will call "abort()"
(or some sub function will)
Thats why its not in an "if (...)"

So NULL or memory address 0, should never happen,
its allocated memory or bust.

Cheers,
        -Tristan

PS:
personaly I prefer the malloc method but when writing
gtk based applications; unless I'm trying to get 
large memory spaces; might as well 
stick with g_new/g_malloc



Gaël Le Mignot wrote:

 > g_new0() is a macro to allocate n structures (the 1 in this case) of a
 > type and zero it out.  You can free the structure just as you said.
 > Your code would work but is a little less concise (ie setting a pointer
 > to NULL and immediately assinging to it with g_malloc()).

But this is broken.
The ISO C doesn't say the binary representation of the NULL pointer must
be 0, in the same way than the binary representation of 0.0 can be very
different from the binary representation of 0.
When you use g_new0() you the memory with bits at 0, which is the
representation of the integer 0, not of the pointer NULL. When you write
(void *) 0, the C compiler convert the 0 into the binary representation of
NULL.

Yes, on common platforms, NULL is binary 0. But it can be different, and
such code can break, since it relies upon something which is not defined
in the ISO C.

 > (If there are any reasons to *not* do it this way, please point them out
 > to me :)

Here it is :)

--
Gael Le Mignot "Kilobug" - kilobug freesurf fr - http://kilobug.free.fr
GSM         : 06.71.47.18.22 (in France)   ICQ UIN   : 7299959
Fingerprint : 1F2C 9804 7505 79DF 95E6 7323 B66B F67B 7103 C5DA

Member of HurdFr: http://hurdfr.org - The GNU Hurd: http://hurd.gnu.org
_______________________________________________
gtk-app-devel-list mailing list
gtk-app-devel-list gnome org
http://mail.gnome.org/mailman/listinfo/gtk-app-devel-list



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]