Groovy hepcat Jason Curl was jivin' on Tue, 16 Nov 2004 18:47:59 +0100
in comp.lang.c.
Definition of NULL's a cool scene! Dig it!
I've been reading this newsgroup for some time and now I am thoroughly
confused over what NULL means.
I've read a NULL pointer is zero (or zero typecast as a void pointer),
others say it's compiler dependent (and that NULL might be anything, but
it is always NULL).
It's really very simple. You're probably confusing three things,
which is a very common error.
1) A null pointer is a pointer guaranteed not to point at an object or
function. The actual representation of a null pointer is not
specified.
2) A null pointer constant is a constant of type int with a value of 0
or such a constant cast to void *. In a pointer context it is
converted to a null pointer.
3) NULL is a macro (defined in various standard C headers) that
evaluates to a null pointer constant.
The source snippet is below. The question is:
- When I use calloc to allocate a block of memory, preinitialising it to
zero, is this equivalent (and portable C) to iterating through the
structure 128 times setting the individual elements to NULL (i.e. is
myFunc() and myFunc2() equivalent in functionality)?
No, not quite. The problem is that calloc() sets the memory it
allocates to "all bits zero". But a null pointer is not necesssarily
"all bits zero". Assigning a null pointer constant (which has the
value 0) to a pointer is guaranteed to make it a null pointer; but
this does not necessarily mean "all bits zero". As stated in point 1)
above, the representation is not specified.
struct _KeySequence {
KeyCallback *cb;
struct _KeySequence *next;
};
struct _KeySequence *node;
int myFunc(void)
{
node = calloc(128, sizeof(struct _KeySequence));
if (node == NULL) {
return 0;
} else {
return 1;
}
}
int myFunc2(void)
{
int j;
node = malloc(128 * sizeof(struct _KeySequence));
if (node == NULL) {
return 0;
} else {
for (j=0; j<127; j++) {
node[j].cb = NULL;
node[j].next = NULL;
}
return 1;
}
}
myFunc2() sets all the pointers in the array to null pointers.
myFunc(), however, may or may not, depending on how null pointers are
represented in the implementation. Technically the value of these
pointers is, therefore, indeterminate.
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?