Pointer initialization is a good way to avoid wild pointers. The initialization is simple and is no different from initialization of a variable.
#include <stddef.h>
int main()
{
int *p1 = NULL;
char *p2 = NULL;
float *p3 = NULL;
/* NULL is a macro defined in stddef.h, stdio.h, stdlib.h, and string.h */
...
}
In most operating systems, inadvertently using a pointer that has been initialized to NULL
will often result in the program crashing immediately, making it easy to identify the cause of the problem. Using an uninitialized pointer can often cause hard-to-diagnose bugs.
The result of dereferencing a NULL
pointer is undefined, so it will not necessarily cause a crash even if that is the natural behaviour of the operating system the program is running on. Compiler optimizations may mask the crash, cause the crash to occur before or after the point in the source code at which the null pointer dereference occurred, or cause parts of the code that contains the null pointer dereference to be unexpectedly removed from the program. Debug builds will not usually exhibit these behaviours, but this is not guaranteed by the language standard. Other unexpected and/or undesirable behaviour is also allowed.
Because NULL
never points to a variable, to allocated memory, or to a function, it is safe to use as a guard value.
Usually NULL
is defined as (void *)0
. But this does not imply that the assigned memory address is 0x0
. For more clarification refer to C-faq for NULL pointers
Note that you can also initialize pointers to contain values other than NULL.
int i1;
int main()
{
int *p1 = &i1;
const char *p2 = "A constant string to point to";
float *p3 = malloc(10 * sizeof(float));
}