There are distinct concepts of null which are similar but do not mean exactly the same, such as:
- The null concept,
- The null pointer constant,
- The NULL macro,
- The ASCII NUL,
- A null string,
- The null statement.
Null assigned to pointer
If the null is assigned to pointer, it means that the pointer doesn’t point to anything. The good practice is to set the pointer to point to NULL if we don’t set a pointer to anything meaningful immediately. The following block of code shows how we can assign null to a pointer:
int main(void)
{
int *ptr;
ptr = NULL;
return (0);
}
What is the idea behind NULL assigned to a pointer?
Again, if the null is assigned to pointer, it means that the pointer doesn’t point to anything. In this case, the pointer can hold a special value and it does not point to any area of memory. Null pointers are always equal to each other.
The NULL macro
The NULL macro is defined in many libraries as:
# define NULL ((void *)0)
The NULL macro is a constant integer zero cast to a pointer to zero. The “NULL” and “0” are language-level symbols representing a null pointer.
The ASCII NUL ”
The ASCII NUL is a byte containing all zeros and is not the same as NULL pointer. In C the string is terminated by a null character (”).
What is the difference between null pointer and uninitialized pointer?
The NULL pointer does not point to any location in memory, whereas the uninitialized pointer can contain any value.
To check if the pointer is set to NULL, we can check following block of code:
if (ptr)
{
// ptr is not NULL
}
else
{
// ptr is NULL
}
Or:
if (ptr == NULL)
// ptr is NULL
if (ptr != NULL)
// ptr is not NULL
Important to note is that null pointer should never be dereferenced as it doesn’t contain any valid address and it will result in the program terminated by signal SIGSEGV (Address boundary error).
Should we assign the pointer to NULL or to 0?
This is completely what you prefer. Both variants are acceptable. However the NULL should not be used if not working with pointers. It can sometimes work but in some cases it could cause problems.
The meaning of zero changes and depends on the context. It can mean an integer 0 or it can mean a null pointer. You can see the example of both in the following block of code.
int number;
int *ptr;
ptr = 0; // Zero refers to the null pointer
number = 100;
ptr = &number;
*ptr = 0; // Zero refers to the integer zero.
SOURCES:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4
[2] Lecture 4: CS50x 2022. CS50x 2022 [online]. 2022 [cit. 2023-03-05]. Available at: https://cs50.harvard.edu/x/2022/notes/4/