views:

110

answers:

3

Lets say I have the following:

 CHARLINK * _init_link(CHARLINK **link)
 {
    short i;
    (*link)->cl = (CHARLINK **) calloc(NUM_CHARS, sizeof(CHARLINK *));
    for (i = 0; i < NUM_CHARS; i++)
        (*link)->cl[i] = NULL;
    return (*link);
}

Is the loop to initialize each element to NULL necessary or are they automatically NULL from calloc?

+2  A: 

No, calloc initializes its buffers to 0's.

Will Hartung
Specifically, it initializes to "all bits 0," which may not be `NULL` (or 0 for `float` values either, for that matter).
Chris Lutz
+6  A: 

That depends a bit on your system, but in the vast majority of cases it's ok. calloc() returns you a buffer filled with zeros. However, the null pointer on your machine might not be a bit pattern of 0. On a machine where the null pointer is non-zero, you might end up in trouble.

Carl Norum
Relying on behavior that usually works but isn't guaranteed to work is a bad idea. Even if you never run into it, wouldn't it be easier to leave the loop and just change the `calloc()` to a `malloc()`, so no one would be tempted to take out the loop and break the code on one of those exotic platforms?
Chris Lutz
+1 @Chris, that's what I'd do.
Carl Norum
correct, correct
Arabcoder
+10  A: 

Yes, the assignment to NULL in the loop is necessary. calloc initialises to all bits 0. But a null pointer may not be represented like that. It is implementation dependent. Thus the assignment is necessary.

Heidelbergensis