NULL pointer in C - GeeksforGeeks (2023)

At a very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are: a) To initialize a pointer variable when that pointer variable hasn’t been assigned any valid memory address yet. b) To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code, e.g., dereference a pointer variable only if it’s not NULL. c) To pass a null pointer to a function argument when we don’t want to pass any valid memory address.

The example of a is

C

int * pInt = NULL;

The example of b is

C

if(pInt != NULL) /*We could use if(pInt) as well*/

{ /*Some code*/}

else

{ /*Some code*/}

The example of c is

C

int fun(int *ptr)

{

/*Fun specific stuff is done with ptr here*/

return 10;

}

fun(NULL);

It should be noted that a NULL pointer is different from an uninitialized or dangling pointer. In a specific program context, all uninitialized or dangling or NULL pointers are invalid, but NULL is a specific invalid pointer which is mentioned in C standard and has specific purposes. What we mean is that uninitialized or dangling pointers are invalid but they can point to some memory address that may be accessible throughunintended memory access.

C

#include <stdio.h>

int main()

{

int *i, *j;

int *ii = NULL, *jj = NULL;

if(i == j)

{

printf("This might get printed if both i and j are same by chance.");

}

if(ii == jj)

{

printf("This is always printed coz ii and jj are same.");

}

return 0;

}

By specifically mentioning NULL pointer, C standard gives a mechanism using which a C programmer can check whether a given pointer is legitimate or not.But what exactly is NULL and how is it defined?Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as “stdio.h”, “stddef.h”, “stdlib.h” etc. Let us see what C standards say about the null pointer. The C11 standard, clause 6.3.2.3 says,

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

Before we proceed further on this NULL discussion :), let’s mention a few lines about C standard just in case youwant to refer to it for further study. Please note that ISO/IEC 9899:2011 is the C language’s latest standard which was published in Dec 2011. This is also called the C11 standard. For completeness, let us mention that the previous C standards were C99, C90 (also known as ISO C) and C89 (also known as ANSI C). Though the actual C11 standard can be purchased from ISO, there’s a draft document which is available in public domains for free.

Coming back to our discussion, the NULL macro is defined as ((void *)0) in the header files of most of the C compiler implementations. But, C standard is saying that 0 is also a null pointer constant. It means that the following is also perfectly legal as per standard:

C

int * ptr = 0;

Please note that 0 in the above C statement is used in pointer-context and it’s different from 0 as integer. This is one of the reasons why the usageof NULL is preferred because it makes it explicit in the code that the programmer is using a null pointer, not integer 0. Another important concept about NULL is that “NULL expands to an implementation-defined null pointer constant”. This statement is also from the C11 standard (clause 7.19). It means that the internal representation of the null pointer could be a non-zero bit pattern to convey the NULL pointer. That’s why NULL doesn’t always need to be internally represented as an all zeros bit pattern. A compiler implementation can choose to represent “null pointer constant” as a bit pattern for all 1s or anything else. But again, as a C programmer, we needn’t worry much about the internal value of the null pointer unless we are involved in compiler coding or even below the level of coding. Having said so, NULL is typically represented as all bits set to 0 only. To know this on a specific platform, one can use the following:

C

#include<stdio.h>

int main()

{

printf("%d",NULL);

return 0;

}

Most likely, it will print 0 which is the typical internal null pointer valuebut again, it can vary depending on the C compiler/platform. You can try a few other things in the above program such as printf(“‘%c“,NULL) or printf(“%s”,NULL) and even printf(“%f”,NULL). The outputs of these are going to be different depending on the platform used but it’d be interesting to see, especially because of the usage of %f with NULL!

Can we use the sizeof() operator on NULL in C? Well, the usage of sizeof(NULL) is allowed but the exact size would depend on the platform.

C

#include<stdio.h>

int main()

{

printf("%lu",sizeof(NULL));

return 0;

}

Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its size would be equal to any pointer. If the pointer size on a platform is 4 bytes, the output of the above program would be 4. But if the pointer size on a platform is 8 bytes, the output of the above program would be 8.

What about dereferencing a NULL pointer? What’s going to happen if we use the following C code:

C

#include<stdio.h>

int main()

{

int * ptr = NULL;

printf("%d",*ptr);

return 0;

}

On some machines, the above would compile successfully but crash when the program is run. Though that doesn’t mean it would show the same behaviour across all the machines. Again, it depends on a lot of factors. But the idea of mentioning the above snippet is that we should always check for NULL before accessing a pointer. As the value of NULL in predefined libraries is 0 and the pointer (that’s pointing to NULL) is not pointing to any memory location, this behaviour occurs.

we can see this code output using diagram:

NULL pointer in C - GeeksforGeeks (1)

Since NULL is typically defined as ((void*)0), let us discuss a little bit about the void type as well. As per C11 standard, clause 6.2.5, “The void type comprises an empty set of values; it is an incomplete object type that cannot be completed”.Even C11 standard, clause 6.5.3.4 mentions that “The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.”Basically, it means that void is an incomplete type whose size doesn’t make any sense in C programs but implementations (such as GCC) can choose sizeof(void) as 1 so that the flat memory pointed to by a void pointer can be viewed as untyped memory i.e. a sequence of bytes. But the output of the following needn’t be same on all platforms:

C

#include<stdio.h>

int main()

{

printf("%lu",sizeof(void));

return 0;

}

On GCC, the above would output 1. What about sizeof(void *)? Here, C11 has mentioned guidelines. From clause 6.2.5, “A pointer to void shall have the same representation and alignment requirements as a pointer to a character type”. That’s why the output of the following would be same as any pointer size on a machine:

C

#include<stdio.h>

int main()

{

printf("%lu",sizeof(void *));

return 0;

}

In spite of mentioning machine dependent stuff as above, we as C programmers should always strive to make our code as portable as possible. So, we can conclude on NULL as follows:

1. Always initialize pointer variables to NULL. 2. Always perform a NULL check before accessing any pointer.

Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us to comment for further clarification or info. We would love to help and learn 🙂


My Personal Notesarrow_drop_up

FAQs

What is a null pointer answer? ›

In the C programming language, a null pointer is a pointer that does not point to any memory location and hence does not hold the address of any variables. It just stores the segment's base address. That is, the null pointer in C holds the value Null, but the type of the pointer is void.

What is the problem with null pointer? ›

A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.

Should you free a null pointer in C? ›

void free(void *ptr); If ptr is a null pointer, no action occurs. Don't check for NULL , it only adds more dummy code to read and is thus a bad practice.

Is a null pointer 0 in C? ›

A null pointer constant is an integer constant expression that evaluates to zero. For example, a null pointer constant can be 0, 0L , or such an expression that can be cast to type (void *)0 .

What is \0 in C? ›

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).

Was the null pointer a mistake? ›

Speaking at a software conference in 2009, Tony Hoare apologized for inventing the null reference: I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W).

Why is null a mistake? ›

The problem with NULL is that it is a non-value value, a sentinel, a special case that was lumped in with everything else. Instead, we need an entity that contains information about (1) whether it contains a value and (2) the contained value, if it exists.

Why should we use null pointer? ›

A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.

How do you handle null pointer? ›

The NullPointerException can be avoided using checks and preventive techniques like the following:
  1. Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
  2. Using Apache Commons StringUtils for String operations e.g. using StringUtils.
Jul 19, 2021

Is free null pointer legal? ›

free(NULL) is perfectly legal in C as well as delete (void *)0 and delete[] (void *)0 are legal in C++. BTW, freeing memory twice usually causes some kind of runtime error, so it does not corrupt anything. delete 0 is not legal in C++. delete explicitly requires an expression of pointer type.

Should you set pointer to null after free? ›

After using free(ptr) , it's always advisable to nullify the pointer variable by declaring again to NULL. e.g.: free(ptr); ptr = NULL; If not re-declared to NULL, the pointer variable still keeps on pointing to the same address (0x1000), this pointer variable is called a dangling pointer.

Should you set pointer to null after delete? ›

I always set a pointer to NULL (now nullptr ) after deleting the object(s) it points to.
  1. It can help catch many references to freed memory (assuming your platform faults on a deref of a null pointer).
  2. It won't catch all references to free'd memory if, for example, you have copies of the pointer lying around.
Dec 18, 2009

Is null guaranteed to be 0? ›

Is NULL guaranteed to be 0? According to the standard, NULL is a null pointer constant (i.e. literal). Exactly which one, is implementation defined. Prior to C++11, null pointer constants were integral constants whose integral value is equal to 0, so 0 or 0l etc.

What is the difference between \0 and 0 in C? ›

\0 is an escape sequence used to represent nothing, really nothing, not even zero! It used to represent Null terminator. On contrast 0 , is as it is, a simple zero.

Can we write 0 instead of null? ›

You cannot use 0 instead of null in your programs even though null is represented by the value 0. You can use null with any reference type including arrays, strings, and custom types.

Why is 1 true and 0 false? ›

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

What is \r in C? ›

\r (Carriage Return) – We use it to position the cursor to the beginning of the current line.

Why is null pointer a billion dollar mistake? ›

Null represents different situations depending on the context in which it is used and invoked. Null is not polymorphic with any object so any function that invokes it will break the chain of subsequent calls. This has led to innumerable errors, vulnerabilities, and system crashes.

IS null always false? ›

Comparing any variable with NULL will always evaluate to FALSE, regardless if it's value, unless IS NULL or IS NOT NULL is used. Violating this rule will affect the functionality of the code. The severity is critical which means that the code will not function correctly.

Can null be false? ›

Nullable boolean can be null, or having a value “true” or “false”. Before accessing the value, we should verify if the variable is null or not.

Does null mean true or false? ›

A null Boolean means that the variable has no reference assigned, so it is neither true nor false, it is “nothing”.

Is null false or true? ›

The null value represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

Is null a good thing? ›

The fundamental problem of null is that it is trying to represent the fact that it is not a value while being assigned as a value. This fundamental flaw then snowballs and manifests into problems that we see in everyday production code.

Why is null better than optional? ›

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.

When should I use null? ›

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

Why null is better than empty string? ›

Sometimes strings can be empty or NULL. The difference is that NULL is used to refer to nothing. However, an empty string is used to point to a unique string with zero length.

How do you avoid null? ›

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

What happens when we access a null pointer in C? ›

Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash. In C, dereferencing a null pointer is undefined behavior.

How do you ignore null? ›

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL. Let's take an example to understand how we can use @JsonInclude annotation to ignore the null fields at the class level.

Can we delete a null pointer? ›

What happens when delete is used for a NULL pointer? Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

Can you reassign a null pointer? ›

What you need to know is that you cannot undo an assignment, so whatever value the pointer contains will be lost. This is the only direct consequence of reassigning a pointer, null or not null. Any problems will be a consequence of no longer having access the previous value.

What happens if you print a null pointer? ›

The Short Answer

Printing null pointers with the %p conversion specifier has undefined behavior.

Do null pointers take up memory? ›

A pointer value ( NULL or not) requires some amount of space to store and represent (4 to 8 bytes on most modern desktop systems, but could be some oddball size depending on the architecture).

How to check if free is successful in C? ›

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.

Does null count as empty? ›

You can think of NULL as an unknown or empty value. A variable is NULL until you assign a value or an object to it.

Is it good to return null? ›

It's very tempting to just return a null reference, but this could cause problems for the caller. If the caller(or callers), fails to do a null check, it could result in a NullPointerException being thrown if some value from the item object is used.

What is rule for null? ›

The following three rules hold for null values: A null is never equal to anything else. None of the following IF statements can ever evaluate to TRUE: my_string := ' '; IF my_string = NULL THEN ...--This will never be true. max_salary := 0; IF max_salary = NULL THEN ...--This will never be true.

Which ignores null values? ›

Answer: A. Except COUNT function, all the group functions ignore NULL values.

Is null and 0 same true or false? ›

The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0.

Is 0 true or false in C? ›

The expressions true == 1 and false == 0 are both true. (And true == 2 is not true).

How do you write a null character? ›

Techopedia Explains Null Character

In programming languages/context, a null character is represented by the escape sequence \0, and it marks the end of a character string.

Why should we return 0 in C? ›

The main function in a C program returns 0 because the main() method is defined and imported first when the code is run in memory. The very first commands within the main() function are implemented. Until all commands of code have been accomplished, the program must be removed from memory.

What can I replace null with? ›

Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0. Cleaning data is important for analytics because messy data can lead to incorrect analysis. Null values can be a common form of messy data.

What is the difference between \0 and '\ 0? ›

"\0" is a string literal which has two consecutive 0's and is roughly equivalent to: const char a[2] = { '\0', '\0' }; '\0' is an int with value 0. You can always 0 wherever you need to use '\0' .

What is the replacement of null in C? ›

nullptr is a new keyword introduced in C++11. nullptr is meant as a replacement to NULL .

What is NullPointerException How do I fix it? ›

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What does the error null pointer assignment means and what causes this error? ›

A NULL pointer assignment is a runtime error It occurs due to various reasons one is that your program has tried to access an illegal memory location. Illegal location means either the location is in the operating systems address space or in the other processes memory space.

What is this null? ›

Null means having no value; in other words null is zero, like if you put so little sugar in your coffee that it's practically null. Null also means invalid, or having no binding force. From the Latin nullus, meaning "not any," poor, powerless null is not actually there at all.

What does null mean in programming? ›

In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address.

How do I stop NullPointerException? ›

Avoiding `NullPointerException` in Java
  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.
Jul 12, 2022

How do you avoid NullPointerException in if condition? ›

To avoid NullPointerException in java programming, always make sure that all the objects are properly initialized before you use them. Before invoking a method on an object, verify that the object is not null while declaring a reference variable.

Is NullPointerException bad? ›

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

What type of error is a null pointer? ›

Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.

Why would a pointer be null? ›

A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.

How to write null in C? ›

The C and C++ languages have a null character (NUL), a null pointer (NULL), and a null statement (just a semicolon (;)). The C NUL is a single character that compares equal to 0.

What is null give example? ›

A null value indicates a lack of a value, which is not the same thing as a value of zero. For example, consider the question "How many books does Adam own?" The answer may be "zero" (we know that he owns none) or "null" (we do not know how many he owns).

How to check if a pointer is null in C? ›

You can usually check for NULL using ptr == 0, but there are corner cases where this can cause an issue. Perhaps more importantly, using NULL makes it obvious that you are working with pointers for other people reading your code.

IS null same as zero? ›

The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0. Considering there is a difference between NULL and 0, the way Tableau treats these two values therefore is different as well.

References

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated: 03/12/2023

Views: 6339

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.