12.8 — Null pointers

Dereferencing a null pointer results in undefined behavior

A pointer should either hold the address of a valid object, or be set to nullptr. That way we only need to test pointers for null, and can assume any non-null pointer is valid.

The first is the literal 0 . In the context of a pointer, the literal 0 is specially defined to mean a null value, and is the only time you can assign an integral literal to a pointer.

DEV Community

DEV Community

AbdulKarim

Posted on Oct 29, 2023

How C-Pointers Works: A Step-by-Step Beginner's Tutorial

In this comprehensive C Pointers tutorial, my primary goal is to guide you through the fundamentals of C pointers from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • What is a Pointer?
  • How Data is Stored in Memory?
  • Storing Memory Addresses using Pointers

Accessing Data through Pointers

  • Pointer Arithmetic
  • Pointer to Pointer (Double Pointers)
  • Passing Pointers as Function Arguments

Arrays of Pointers

Null pointers, prerequisite:.

To grasp pointers effectively, you should be comfortable with basic C programming concepts, including variables, data types, functions, loops, and conditional statements. This familiarity with C programming forms the foundation for understanding how pointers work within the language. Once you have a solid grasp of these fundamental concepts, you can confidently delve into the intricacies of C pointers.

What is a pointer?

A pointer serves as a reference that holds the memory location of another variable. This memory address allows us to access the value stored at that location in the memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory

Pointers can be a challenging concept for beginners to grasp, but in this tutorial, I'll explain them using real-life analogies to make the concept clearer. However, Before delving into pointers and their workings, it's important to understand the concept of a memory address.

A memory address is a unique identifier that points to a specific location in a computer's memory. Think of it like a street address for data stored in your computer's RAM (Random Access Memory). Just as a street address tells you where a particular house is located in the physical world, a memory address tells the computer where a specific piece of information or data is stored in its memory.

Take a look at the image below for a better understanding:

Block of memory

In this illustration, each block represents one byte of memory. It's important to note that every byte of memory has a unique address. To make it easier to understand, I've represented the addresses in decimal notation, but computers actually store these addresses using hexadecimal values. Hexadecimal is a base-16 numbering system commonly used in computing to represent memory addresses and other low-level data. It's essential to be aware of this representation when working with memory-related concepts in computer programming

How data is stored in the memory:

Every piece of data in your computer, whether it's a number, a character, or a program instruction, is stored at a specific memory address. The amount of space reserved for each data type can vary, and it is typically measured in bytes (where 1 byte equals 8 bits, with each bit representing either 0 or 1). The specific sizes of data types also depend on the computer architecture you are using. For instance, on most 64-bit Linux machines, you'll find the following typical sizes for common data types: char = 1 byte int = 4 bytes float = 4 bytes double = 8 bytes These sizes define how much memory each data type occupies and are crucial for memory management and efficient data representation in computer systems.

You can use the sizeof operator to determine the size of data types on your computer. example:

In this example: sizeof(char) returns the size of the char data type in bytes. sizeof(int) returns the size of the int data type in bytes. sizeof(float) returns the size of the float data type in bytes. sizeof(double) returns the size of the double data type in bytes. When you run this code, it will print the sizes of these data types on your specific computer, allowing you to see the actual sizes used by your system.

When you declare a variable, the computer allocates a specific amount of memory space corresponding to the chosen data type. For instance, when you declare a variable of type char, the computer reserves 1 byte of memory because the size of the 'char' data type is conventionally 1 byte.

address of char n

In this example, we declare a variable n of type char without assigning it a specific value. The memory address allocated for the n variable is 106 . This address, 106 , is where the computer will store the char variable n, but since we haven't assigned it a value yet, the content of this memory location may initially contain an unpredictable or uninitialized value.

When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n. When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n.

address of cahr n = c

As mentioned earlier, a byte can only store numerical values. When we store the letter 'C' in a byte, the byte actually holds the ASCII code for 'C,' which is 67. In computer memory, characters are represented using their corresponding ASCII codes. So, in memory, the character 'C' is stored as the numerical value 67. Here's how it looks in memory

Ascii code of c

Since integers are typically stored within four bytes of memory, let's consider the same example with an int variable. In this scenario, the memory structure would appear as follows:

add. of int t

In this example, the memory address where the variable t is stored is 121. An int variable like “t” typically uses four consecutive memory addresses, such as 121, 122, 123, and 124. The starting address, in this case, 121, represents the location of the first byte of the int, and the subsequent addresses sequentially represent the following bytes that collectively store the complete int value.

If you want to know the memory address of a variable in a program, you can use the 'address of' unary operator, often denoted as the '&' operator. This operator allows you to access the specific memory location where a variable is stored.

When you run the following program on your computer: It will provide you with specific memory addresses for the variables c and n. However, each time you rerun the program, it might allocate new memory addresses for these variables. It's important to understand that while you can determine the memory address of a variable using the & operator, the exact memory location where a variable is stored is typically managed by the system and the compiler. As a programmer, you cannot directly control or assign a specific memory location for a variable. Instead, memory allocation and management are tasks handled by the system and the compiler.

Storing memory address using pointers

As mentioned earlier, a pointer is a variable that stores the memory address of another variable. This memory address allows us to access the value stored at that location in memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory.

Now, let's begin by declaring and initializing pointers. This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location.

Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, we've declared a pointer named ptr that can point to integers.

Memory of Declaring an integer pointer

The size of pointers on 64-bit systems is usually 8 bytes (64 bits). To determine the pointer size on your system, you can use the sizeof operator:

Initializing Pointers: Once you've declared a pointer, you typically initialize it with the memory address it should point to. Once again, To obtain the memory address of a variable, you can employ the address-of operator (&). For instance:

In this program:

We declare an integer variable x and initialize it with the value 10. This line creates a variable x in memory and assigns the value 10 to it.

ptr

We declare an integer pointer ptr using the int *ptr syntax. This line tells the compiler that ptr will be used to store the memory address of an integer variable.

pointrt to ptr

We initialize the pointer ptr with the memory address of the variable x . This is achieved with the line ptr = &x; . The & operator retrieves the memory address of x, and this address is stored in the pointer ptr .

address of variable x

Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values. To get the actual value (data) stored at that memory address, you need to dereference the pointer.

Dereferencing is done using the asterisk (*) operator. Here's an example:

It looks like this in the memory: int x = 10; variable 'x' stores the value 10:

var X

int *ptr = &x; Now, the pointer 'ptr' point to the address of 'x':

Pointer to X

int value = *ptr; Dereference 'ptr' to get the value stored at the address it points to:

pointer value is 10

Reading and Modifying Data: Pointers allow you to not only read but also modify data indirectly:

Note: The asterisk is a versatile symbol with different meanings depending on where it's used in your C program, for example: Declaration: When used during variable declaration, the asterisk (*) indicates that a variable is a pointer to a specific data type. For example: int *ptr; declares 'ptr' as a pointer to an integer.

Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to.

Pointer Arithmetic:

Pointer arithmetic is the practice of performing mathematical operations on pointers in C. This allows you to navigate through arrays, structures, and dynamically allocated memory. You can increment or decrement pointers, add or subtract integers from them, and compare them. It's a powerful tool for efficient data manipulation, but it should be used carefully to avoid memory-related issues.

Incrementing a Pointer:

Now, this program is how it looks in the memory: int arr[4] = {10, 20, 30, 40};

int arr

This behavior is a key aspect of pointer arithmetic. When you add an integer to a pointer, it moves to the memory location of the element at the specified index, allowing you to efficiently access and manipulate elements within the array. It's worth noting that you can use pointer arithmetic to access elements in any position within the array, making it a powerful technique for working with arrays of data. Now, let's print the memory addresses of the elements in the array from our previous program.

If you observe the last two digits of the first address is 40, and the second one is 44. You might be wondering why it's not 40 and 41. This is because we're working with an integer array, and in most systems, the size of an int data type is 4 bytes. Therefore, the addresses are incremented in steps of 4. The first address shows 40, the second 44, and the third one 48

Decrementing a Pointer Decrement (--) a pointer variable, which makes it point to the previous element in an array. For example, ptr-- moves it to the previous one. For example:

Explanation:

We have an integer array arr with 5 elements, and we initialize a pointer ptr to point to the fourth element (value 40) using &arr[3].

Then, we decrement the pointer ptr by one with the statement ptr--. This moves the pointer to the previous memory location, which now points to the third element (value 30).

Finally, we print the value pointed to by the decremented pointer using *ptr, which gives us the value 30.

In this program, we demonstrate how decrementing a pointer moves it to the previous memory location in the array, allowing you to access and manipulate the previous element.

Pointer to pointer

Pointers to pointers, or double pointers, are variables that store the address of another pointer. In essence, they add another level of indirection. These are commonly used when you need to modify the pointer itself or work with multi-dimensional arrays.

To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example:

In this example, ptr2 is a pointer to a pointer. It points to the memory location where the address of x is stored (which is ptr1 ).

pointer to poiter

The below program will show you how to print the value of x through pointer to pointer

In this program, we first explain that it prints the value of x using a regular variable, a pointer, and a pointer to a pointer. We then print the memory addresses of x , ptr1 , and ptr2 .

Passing Pointers as Function Arguments:

In C, you can pass pointers as function arguments. This allows you to manipulate the original data directly, as opposed to working with a copy of the data, as you would with regular variables. Here's how it works:

How to Declare and Define Functions that Take Pointer Arguments: In your function declaration and definition, you specify that you're passing a pointer by using the * operator after the data type. For example:

In the above function, we declare ptr as a pointer to an integer. This means it can store the memory address of an integer variable.

Why Would You Pass Pointers to Functions?

Passing pointers to functions allows you to:

  • Modify the original data directly within the function.
  • Avoid making a copy of the data, which can be more memory-efficient.
  • Share data between different parts of your program efficiently.

This concept is especially important when working with large data structures or when you need to return multiple values from a function.

Call by Value vs. Call by Reference:

Understanding how data is passed to functions is crucial when working with pointers. there are two common ways that data can be passed to functions: call by value and call by reference.

Call by Value:

When you pass data by value, a copy of the original data is created inside the function. Any modifications to this copy do not affect the original data outside of the function. This is the default behavior for most data types when you don't use pointers.

Call by Reference (Using Pointers):

When you pass data by reference, you're actually passing a pointer to the original data's memory location. This means any changes made within the function will directly affect the original data outside the function. This is achieved by passing pointers as function arguments, making it call by reference. Using pointers as function arguments allows you to achieve call by reference behavior, which is particularly useful when you want to modify the original data inside a function and have those changes reflected outside the function.

Let's dive into some code examples to illustrate how pointers work as function arguments. We'll start with a simple example to demonstrate passing a pointer to a function and modifying the original data.

Consider this example:

In this code, we define a function modifyValue that takes a pointer to an integer. We pass the address of the variable num to this function, and it doubles the value stored in num directly.

This is a simple demonstration of passing a pointer to modify a variable's value. Pointers allow you to work with the original data efficiently.

An array of pointers is essentially an array where each element is a pointer. These pointers can point to different data types (int, char, etc.), providing flexibility and efficiency in managing memory.

How to Declare an Array of Pointers? To declare an array of pointers, you specify the type of data the pointers will point to, followed by square brackets to indicate it's an array, and then the variable name. For example:

Initializing an Array of Pointers You can initialize an array of pointers to each element to point to a specific value, For example:

How to Access Elements Through an Array of Pointers? To access elements through an array of pointers, you can use the pointer notation. For example:

This program demonstrates how to access and print the values pointed to by the pointers in the array.

A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers.

Here's a code example that demonstrates the use of a NULL pointer:

In this example, we declare a pointer ptr and explicitly initialize it with the value NULL. We then use an if statement to check if the pointer is NULL. Since it is, the program will print "The pointer is NULL." This illustrates how NULL pointers are commonly used to check if a pointer has been initialized or assigned a valid memory address.

conclusion:

You've embarked on a comprehensive journey through the intricacies of C pointers. You've learned how pointers store memory addresses, enable data access, facilitate pointer arithmetic, and how they can be used with arrays and functions. Additionally, you've explored the significance of NULL pointers.

By completing this tutorial, you've equipped yourself with a robust understanding of pointers in C. You can now confidently navigate memory, manipulate data efficiently, and harness the power of pointers in your programming projects. These skills will be invaluable as you advance in your coding endeavors. Congratulations on your accomplishment, and keep coding with confidence!

Reference: C - Pointers - Tutorials Point

Pointers in C: A One-Stop Solution for Using C Pointers - simplilearn

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

imperiald profile image

  • Joined Jan 7, 2024

Love your way to write articles, could you add an article for, .o files, .h files, lists and makefile? Thank you in advance!

cocomelonjuice profile image

  • Joined Nov 4, 2023

Great post. Thank you so much for this.

koderkareem profile image

Thank you for your kind words! I'm thrilled to hear that you enjoyed the article. Your feedback means a lot to me. If you have any questions or if there's a specific topic you'd like to see in future posts, feel free to let me know. Thanks again for your support

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

raulpenate profile image

Clean Code vs Mejores Prácticas: ¿Cuál es la Diferencia?

Raúl Peñate - Sep 8

devops_den profile image

Create a Wordle Game in HTML,CSS, and JS

Devops Den - Sep 8

surajondev profile image

GitHub Repos Essential for Every React Developer

Suraj Vishwakarma - Sep 9

jayantbh profile image

Frontend Dev + Data Structures & Algorithms: How DSA Can Power Your React App ⚡

Jayant Bhawal - Sep 8

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

EDUCBA

Null pointer in C

Abhilasha Chougule

Updated March 28, 2023

Null pointer in C

Introduction to Null pointers in C

In C programming language, a variable that can point to or store the address of another variable is known as pointers. In C programming language pointers are used to point to the memory that is allocated dynamically or at run time and a pointer can be of any data type like int, float, char, etc. In this article, we are discussing the null pointer in C, where NULL is constant with value 0 in C. So the null pointer is defined as the pointer that is assigned to zero to make it null pointer or a pointer that does not store any valid memory address or an uninitialized pointer are known as a NULL pointer. In general, we can a pointer that does not point to any object is known as a null pointer.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How does Null pointer work in C?

A null pointer in C is a pointer that is assigned to zero or NULL where a variable that has no valid address. The null pointer usually does not point to anything. In C programming language NULL is a macro constant that is defined in a few of the header files like stdio.h, alloc.h, mem.h, stddef.h, stdlib.h. Also, note that NULL should be used only when we are dealing with pointers only. Simple syntax for declaring NULL pointer is as follows:

We can directly assign the pointer variable to 0 to make it null pointer.

Examples to Implement Null pointer in C

Let us see an example of how null pointers are created.

0 (zero)

Explanation: In the above code, we are initializing the variable “ptr”  to 0 (zero) so when we print the pointer value which Null pointer.

Suppose let us take another example where the pointer variables are not assigned to any memory address.

timeout

Explanation: In the above code, the pointer_var variable is not assigned to zero nor it stores any address of any variable in it, when the code is executed during the compile-time it gives an error where it throws garbage value which might harm your computer. So usually when we try to write or read from a null pointer we get run time error as we saw in the above code which we get segmentation fault which is a null pointer exception sometimes it also throws an exception as null pointer exception. In most of the examples, a null pointer is used to denote or indicate the end of the list.

To avoid this exception we can rewrite the above code as

Null pointer in C - 3

Explanation: In the above-modified code, we assign a pointer_var to the “NULL” value and we check with the condition if the value of the pointer is null or not. In most of the operating system, codes or programs are not allowed to access any memory which has its address as 0 because the memory with address zero 0is only reserved by the operating system as it has special importance, which states that the pointer is not intended to point to any memory location that can be accessible. So by default, we can say that if a pointer is assigned to zero then it is nothing but it only points to nothing.

So there is a way to check for the pointer is null or not by using if(ptr) results in 1 if the pointer is not null and if(!ptr)  results in 1 when the pointer is null as we did in the above-modified program.

Let us see the use of null pointers in C programming language as below:

Null pointers are used to avoid crashing down of the program: As we saw earlier if we declare any pointer without assigning anything to it then it takes garbage value where it may result in crashing of the system program. So to avoid such situations we use null pointers where variables are assigned or declared as NULL or zero which is known as a null pointer.

Null pointer in C - 4

Explanation: In the above code, we are defining function func() where we are passing a pointer ptrvarA and when the function func() is called it checks if the passed pointer is a null pointer or not. So we have to check if the passed value of the pointer is null or not because if it is not assigned to any value it will take the garbage value and it will terminate your program which will lead to the crashing of the program.

  • Another use is when we are freeing up the memory locations: In a few cases we do not need the memory data anymore where we are again pointing to the same memory then we delete that data to free up the memory. But the pointer is still pointing to the same memory location even after deleting the data from that memory. Such pointers are called dangling pointers this also can be avoided by using null pointer by setting the dangling pointer to null.

In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro. And we should note that once the data is not in use the memory allocated to it must be freed else it will again lead to the dangling pointer. And also note that never declare any pointer without assigning NULL because the program when executes it throws an error during runtime.

Recommended Articles

This is a guide to Null pointer in C. Here we discuss how Null pointer work in C  with syntax and examples to implement with proper codes and outputs. You can also go through our other related articles to learn more –

  • Pointers in C++
  • Pointers in C#
  • Pointers in C
  • Pointers in Python

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy .

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Quiz

Explore 1000+ varieties of Mock tests View more

Submit Next Question

Early-Bird Offer: ENROLL NOW

quiz

C++ Tutorial

  • C++ Overview
  • C++ Environment Setup
  • C++ Basic Syntax
  • C++ Comments
  • C++ Data Types
  • C++ Numeric Data Types
  • C++ Character Data Type
  • C++ Boolean Data Type
  • C++ Variable Types
  • C++ Variable Scope
  • C++ Multiple Variables
  • C++ Basic Input/Output
  • C++ Constants/Literals
  • C++ Modifier Types
  • C++ Storage Classes
  • C++ Operators
  • C++ Decision Making
  • C++ Loop Types
  • C++ Functions
  • C++ Numbers
  • C++ Strings
  • C++ String Length
  • C++ String Concatenation
  • C++ Pointers
  • C++ References
  • C++ Date & Time
  • C++ Structures
  • C++ Object Oriented
  • C++ Classes & Objects
  • C++ Inheritance
  • C++ Overloading
  • C++ Polymorphism
  • C++ Abstraction
  • C++ Encapsulation
  • C++ Interfaces
  • C++ Advanced
  • C++ Files and Streams
  • C++ Exception Handling
  • C++ Dynamic Memory
  • C++ Namespaces
  • C++ Templates
  • C++ Preprocessor
  • C++ Signal Handling
  • C++ Multithreading
  • C++ Web Programming
  • C++ - Advanced Concepts
  • C++ Useful Resources
  • C++ Questions and Answers
  • C++ Quick Guide
  • C++ Cheat Sheet
  • C++ STL Tutorial
  • C++ Standard Library
  • C++ Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C++ Null Pointers

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program −

When the above code is compiled and executed, it produces the following result −

On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.

To check for a null pointer you can use an if statement as follows −

Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables hold some junk values and it becomes difficult to debug the program.

C++ Null Pointers with examples

explain null pointer assignment

In this tutorial, we will learn about null pointers in C++ and see various uses of null pointers with some examples. I will try to make this tutorial easy to understand. Let’s get started.

Null Pointers in C++

A NULL pointer is a special type of pointer that does not point to any memory location. In other words, we can say that a pointer represents an invalid location. Whenever a value is assigned as  NULL to a pointer, then that pointer is considered as a NULL pointer. NULL is itself a special type of pointer. When we initialize a pointer with NULL then that pointer also becomes a NULL pointer.

Example to understand what is a NULL pointer.

Let’s see some uses of NULL pointer:

  • It is used to initialize a pointer when that pointer isn’t assigned any valid memory address yet. That is it’s a good practice to assign a pointer with null if a not valid address is defined.

To check pointer is null or not.

It is not a NULL POINTER.

Hope you liked this tutorial. Happy Learning !!

Also Read:  How to set a pointer to null in C++

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Please enable JavaScript to submit this form.

Related Posts

  • Difference between NULL and nullptr in C++
  • Dereferencing a nullptr in C++
  • Pass NULL value as function parameter in C++

Basic Programs

  • Hello World
  • Taking Input from User
  • Find ASCII Value of Character
  • Using gets() function
  • Switch Case
  • Checking for Vowel
  • Reversing Case of Character
  • Swapping Two Numbers
  • Largest and Smallest using Global Declaration
  • Basic for Loop
  • Basic while Loop
  • Basic do-while Loop
  • Nested for Loops
  • Program to find Factorial of number
  • Fibonacci Series Program
  • Palindrome Program
  • Program to find Sum of Digits
  • Program to reverse a String
  • Program to find Average of n Numbers
  • Armstrong Number
  • Checking input number for Odd or Even
  • Print Factors of a Number
  • Find sum of n Numbers
  • Print first n Prime Numbers
  • Find Largest among n Numbers
  • Exponential without pow() method
  • Find whether number is int or float
  • Print Multiplication Table of input Number
  • Reverse an Array
  • Insert Element to Array
  • Delete Element from Array
  • Largest and Smallest Element in Array
  • Sum of N Numbers using Arrays
  • Sort Array Elements
  • Remove Duplicate Elements
  • Sparse Matrix
  • Square Matrix
  • Determinant of 2x2 matrix
  • Normal and Trace of Square Matrix
  • Addition and Subtraction of Matrices
  • Matrix Mulitplication
  • Simple Program
  • Memory Management
  • Array of Pointers
  • Pointer Increment and Decrement
  • Pointer Comparison
  • Pointer to a Pointer
  • Concatenate Strings using Pointer
  • Reverse a String using Pointer
  • Pointer to a Function
  • Null Pointer
  • isgraph() and isprint()
  • Removing Whitespaces
  • gets() and strlen()
  • strlen() and sizeof()
  • Frequency of characters in string
  • Count Number of Vowels
  • Adding Two Numbers
  • Fibonacci Series
  • Sum of First N Numbers
  • Sum of Digits
  • Largest Array Element
  • Prime or Composite
  • LCM of Two Numbers
  • GCD of Two Numbers
  • Reverse a String

Files and Streams

  • List Files in Directory
  • Size of File
  • Write in File
  • Reverse Content of File
  • Copy File to Another File

Important Concepts

  • Largest of three numbers
  • Second largest among three numbers
  • Adding two numbers using pointers
  • Sum of first and last digit
  • Area and Circumference of Circle
  • Area of Triangle
  • Basic Arithmetic Operations
  • Conversion between Number System
  • Celsius to Fahrenheit
  • Simple Interest
  • Greatest Common Divisor(GCD)
  • Roots of Quadratic Roots
  • Identifying a Perfect Square
  • Calculate nPr and nCr

Miscellaneous

  • Windows Shutdown
  • Without Main Function
  • Menu Driven Program
  • Changing Text Background Color
  • Current Date and Time

Using Null Pointer Program

NULL is a macro in C, defined in the <stdio.h> header file, and it represent a null pointer constant. Conceptually, when a pointer has that Null value it is not pointing anywhere.

If you declare a pointer in C, and don't assign it a value, it will be assigned a garbage value by the C compiler, and that can lead to errors.

Void pointer is a specific pointer type. void * which is a pointer that points to some data location in storage, which doesn't have any specific type.

Don't confuse the void * pointer with a NULL pointer.

NULL pointer is a value whereas, Void pointer is a type.

Below is a program to define a NULL pointer.

Program Output:

C program example for Null Pointer

Use Null Pointer to mark end of Pointer Array in C

Now let's see a program in which we will use the NULL pointer in a practical usecase.

We will create an array with string values ( char * ), and we will keep the last value of the array as NULL. We will also define a search() function to search for name in the array.

Inside the search() function, while searching for a value in the array, we will use NULL pointer to identify the end of the array.

So let's see the code,

Peter is in the list. Scarlett not found.

This is a simple program to give you an idea of how you can use the NULL pointer. But there is so much more that you can do. You can ask the user to input the names for the array. And then the user can also search for names. So you just have to customize the program a little to make it support user input.

  • ← Prev
  • Next →

  C Tutorial

  c mcq tests.

CSEstack

3 Major use of NULL Pointer in C Programming | What does actually NULL means?

Aniruddha chaudhari.

  • Updated: Mar 09, 2019

Understanding the NULL pointer is easy but not so if you are implementing in your code. At the end of this post, you will learn to avoid NULL pointer problems and handling them gracefully.

Following are the topics covered in this article.

Table of Contents

  • What is a NULL?

What is a NULL Pointer?

Why do we need a null pointer.

  • Best Practices to use NULL Pointer
  • What is the use of NULL Pointer in C?
  • Difference Between NULL and Void Pointer
  • Usage of a NULL Pointer in Various Programming Languages

So let’s begin…

What is NULL?

It is a special marker or keyword which has no value.

Each programming language has its own nuance.

In most of the programming language including C, Java, typically, 0 (zero) is a NULL and predefined constant or Macro.

NULL is a value that is not a value. Confusing, right?

Here is a simple example to differentiate.

In C++ programming,

char *par = 123; is not valid and gives a compilation error. Compiler except passing a hexadecimal value to the pointer and we are passing integer value.

Whereas  char *par = 0; is a valid statement. Here, 0 (zero) is a null in C++ programming. As null does not have any value, the compiler can not discriminate.

For this reason, C.A.R Hoare (inventor of Null) said that inventing the NULL pointer was his biggest mistake. We leave this here, as it is not the scope of this article.

Moving to…

Whenever you assign any data to the variable, it gets stored at a particular location in the physical memory. This memory location has unique address value in hexadecimal format (something like 0x006CoEEA8 ).

The variable that stores this memory address is called as a  Pointer .

When you assign a NULL value to the pointer, it does not point to any of the memory locations. The null pointer is nothing but the pointer which points to nothing.

It is also called as a NULL macro .

Here is a simple C program to print the value of NULL macro.

We can use this NULL constant value to assign to any pointer so that it will not point to any of the memory locations.

Here is the simple syntax for declaring a NULL pointer.

Here, ptr is a NULL pointer.

We can also assign 0 directly to the pointer.

This is also a valid expression in C. But, it is a standard practice to use a NULL constant.

The NULL constant is defined in many of the header files in the C programming language; including,  stdio.h   stddef.h , stdlib.h , etc.

In C programming, usually, we add stdio.h in the program to use scanf() and printf() functions. So, you don’t need to add any extra header files.

Later in the code, you can assign any memory location to ptr pointer.

Whenever you declare a pointer in your program, it points to some random memory location. And when you try to retrieve the information at that location, you get some garbage values. Many time, you might have observed this.

Using this garbage value in the program or passing it to any function, your program may crash.

Here, NULL pointer comes handy.

I am describing the use of the NULL pointer in C programming by three different ways. Before that, let’s see the best practices to use NULL pointer in programming.

Best Practices for NULL Pointer Usage:

How to use a NULL pointer to avoid any errors in your programming?

  • Make a habit of assigning the value to a pointer before using it. Don’t use pointer before initializing it.
  • If you don’t have a valid memory address to store in a pointer variable, just initialize a pointer to NULL.
  • Before using a pointer in any of your function code, check if it has not a NULL value.

What is the use of NULL Pointer in C?

Above all understanding, this is the first question you ask yourself about the NULL pointer. Here are some use cases of NULL pointer…

1. Avoid Crashing a Program:

If you pass any garbage value in your code or to the particular function, your program can crash. To avoid this, you can use NULL pointer.

Before using any pointer, compare it with NULL value and check.

In the above code, we are passing a pointer to fact() function. In fact() function, we are checking if the input pointer is NULL or not.

If the value of the pointer ptrA is not NULL, execute the function body.

Passing a NULL value to the function code without checking can terminate your program by crashing inside the function. So, it is one of the best use of NULL pointer in C.

2. While Freeing (de-allocating) Memory:

Suppose, you have a pointer which points to some memory location where data is stored. If you don’t need that data anymore, for sure, you want to delete that data and free the memory.

But even after freeing the data, pointer still points to the same memory location. This pointer is called as a dangling pointer . To avoid this dangling pointer, you can set the pointer to NULL.

Let’s check this below example to avoid dangling pointer in C.

Here, malloc() is an inbuilt function to create a dynamic memory.

What is the difference between NULL and Void Pointer?

Many of the programmer, especially beginners, get confused between NULL and void pointer.

The void is one of the data types in C. Whereas, NULL is the value which is assigned to the pointer.

The data type of the pointer is nothing but the type of data stored at the memory location where the pointer is pointed. When you are not sure about the type of data that is going to store at a particular memory location, you need to create the void pointer .

Below is an example for creating void pointer in C.

3. NULL pointer Uses in Linked List:

A NULL pointer is also useful in Linked List. We know that in Linked List, we point one node to its successor node using a pointer.

Implement Linked List in C

As there is no successor node to the last node, you need to assign a NULL value to the link of the last node. (As shown in above image.)

Check the implementation of Linked List in C to know how NULL pointer is used. I have described it in detail.

This is all about NULL pointer in C and CPP programming. The understanding of the NULL pointer is a concept. Like C programming, you can see the same use cases of NULL pointers in many other programming languages.

Usage of a NULL pointer in various Programming Languages?

Many of the programming languages use the NULL pointer concept. It is not necessary to have the same name for a NULL pointer, but the concept is almost the same in all the programming languages.

  • In C, the NULL keyword is a predefined macro.
  • In C++, the NULL is inherited from C programming.
  • The latest development in C++11, there is an explicit pointer to handle the NULL exception, called null ptr constant.
  • In Java programming , there is a null value. It indicates that no value is assigned to a reference variable.
  • In some other programming language like Lips, it is called as nil vector .

Check out all the C and C++ programming questions . You will find NULL pointer and macro very useful.

This is all about NULL macro and use of NULL pointer in C programming. If you have any question, feel free to ask in a comment.

Aniruddha Chaudhari

I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.

Great Post. Agree with Mathew. Many people learn about NULL pointer but many few uses them in their project.

I think the NULL pointer is extremely useful to avoid the crash and for better programming.

You are absolutely right, Vatsal. Thanks for putting your thought.

I read about NULL pointer earlier, but this is very descriptive and you have mentioned very good use cases.

Thanks Aniruddha.

Great to see you here Mathew. I am glad you like it.

Very neatly explained. Thank you and keep up the good work. 🙂

Thanks Abha for putting your thought 🙂 It keeps motivating me to work hard.

output is 10. It still works. My program is not crashed.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

C Programming

  • C- Introduction
  • C- Compile & Execute Program
  • C- Data Types
  • C- if-else statement
  • C- While, do-while, for loop
  • C- Function (Types/Call)
  • C- strlen() vs sizeof()
  • C- Nested Switch Statement
  • C- Recursion
  • C- Dynamic Programming
  • C- Storage Classes
  • C- Creating Header File
  • C- Null Pointer
  • C- Stack and Queue
  • C- Implement Stack using Array
  • C- Implement Linked List in C
  • C- File Handling
  • C- Makefile Tutorial

Programming for Practice

  • Online C/C++ Compiler

String Handling:

  • Remove White Spaces from String
  • Implement strstr Function in C
  • Convert String to Int – atoi()
  • Check if String is Palindrome
  • Check if Two Strings are Anagram
  • Split String in using strtok_r()
  • Undefined reference to strrev
  • Check if Array is Sorted

Bit Manipulation:

  • Count Number of 1’s in Binary

Linked List:

  • Reverse a Linked List Elements

Number System:

  • Program to Find 2’s Complement
  • Convert Decimal to Binary in C

Tricky Questions:

  • Add Two Numbers without Operator
  • Find Next Greater Number
  • Swap values without temp variable
  • Print 1 to 100 without Loop

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

web analytics

  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Null Pointer Exception In Java

NullPointerException is a RuntimeException. In Java , a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.

Reason for Null Pointer Exception

These are certain reasons for Null Pointer Exception as mentioned below: 

  • Invoking a method from a null object.
  • Accessing or modifying a null object’s field.
  • Taking the length of null, as if it were an array.
  • Accessing or modifying the slots of null objects, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Why do we need the Null Value?  

Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. One application of null is in implementing data structures like linked lists and trees. Other applications include the Null Object pattern (See this for details) and the Singleton pattern . The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.

A simple way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:

           

Output: 

In above example, a static instance of the singleton class. That instance is initialized at most once inside the Singleton getInstance method.

How to Avoid the NullPointerException?  

To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects. Following are the common problems with the solution to overcome that problem.

Case 1 : String comparison with literals

A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. 

Below is the Example of the Case 1:

     

We can avoid NullPointerException by calling equals on literal rather than object.

     

Case 2 : Keeping a Check on the arguments of a method

Before executing the body of your new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments. 

Below is the Example of the Case 2:

               

Case 3 : Use of Ternary Operator

The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers:

     

The message variable will be empty if str’s reference is null as in case

  • Otherwise, if str point to actual data , the message will retrieve the first 6 characters of it as in case
  • Related Article – Interesting facts about Null in Java  

Frequently Asked Questions

1. what is nullpointerexception in java.

NullPointerException in Java is a type RuntimeException.

2. Why Null Pointer Exception Occurs?

NullPointerException occurs when one tries to access or manipulate object reference that has a Null value stored in it.

3. How to handle a Null Pointer Exception in Java?

There are certain methods to handle Null Pointer Exception in Java are mentioned below: String comparison with literals Keeping a Check on the arguments of a method Use of Ternary Operator

4. Reason for Null Pointer Exception.

NullPointerException is thrown when a program attempts to use an object reference that has the null value.

Please Login to comment...

Similar reads.

  • Technical Scripter
  • Exception Handling
  • Java-Exceptions
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 10 Best Free VPN Services in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

A quick and thorough guide to ‘null’: what it is, and how you should use it

freeCodeCamp

By Christian Neumanns

What is the meaning of null ? How is null implemented? When should you use null in your source code, and when should you not use it?

Image

Introduction

null is a fundamental concept in many programming languages. It is ubiquitous in all kinds of source code written in these languages. So it is essential to fully grasp the idea of null . We have to understand its semantics and implementation, and we need to know how to use null in our source code.

Comments in programmer forums sometimes reveal a bit of confusion with null . Some programmers even try to completely avoid null . Because they think of it as the 'million-dollar mistake', a term coined by Tony Hoare, the inventor of null .

Here is a simple example: Suppose that Alice’s email_address points to null . What does this mean? Does it mean that Alice doesn't have an email address? Or that her email address is unknown? Or that it is secret? Or does it simply mean that email_address is 'undefined' or 'uninitialized'? Let's see. After reading this article, everybody should be able to answer such questions without hesitation.

Note: This article is programming-language-neutral — as far as possible. Explanations are general and not tied to a specific language. Please consult your programming language manuals for specific advice on null . However, this article contains some simple source code examples shown in Java. But it’s not difficult to translate them into your favorite language.

Run-time Implementation

Before discussing the meaning of null , we need to understand how null is implemented in memory at run-time.

Note: We will have a look at a typical implementation of null . The actual implementation in a given environment depends on the programming language and target environment, and might differ from the implementation shown here.

Suppose we have the following source code instruction:

Here we declare a variable of type String and with the identifier name that points to the string "Bob" .

Saying “points to” is important in this context, because we are assuming that we work with reference types (and not with value types ). More on this later.

To keep things simple, we will make the following assumptions:

  • The above instruction is executed on a 16-bits CPU with a 16-bits address space.
  • Strings are encoded as UTF-16. They are terminated with 0 (as in C or C++).

The following picture shows an excerpt of the memory after executing the above instruction:

Image

The memory addresses in the above picture are chosen arbitrarily and are irrelevant for our discussion.

As we can see, the string "Bob" is stored at address B000 and occupies 4 memory cells.

Variable name is located at address A0A1. The content of A0A1 is B000, which is the starting memory location of the string "Bob" . That's why we say: The variable name points to "Bob" .

So far so good.

Now suppose that, after executing the above instruction, you execute the following:

Now name points to null .

And this is the new state in memory:

Image

We can see that nothing has changed for the string "Bob" which is still stored in memory.

Note: The memory needed to store the string "Bob" might later be released if there is a garbage collector and no other reference points to "Bob" , but this is irrelevant in our discussion.

What’s important is that the content of A0A1 (which represents the value of variable name ) is now 0000. So, variable name doesn't point to "Bob" anymore. The value 0 (all bits at zero) is a typical value used in memory to denote null . It means that there is no value associated with name . You can also think of it as the absence of data or simply no data .

Note: The actual memory value used to denote null is implementation-specific. For example the Java Virtual Machine Specification states at the end of section _2.4. “_Reference Types and Values:”

The Java Virtual Machine specification does not mandate a concrete value encoding null .

If a reference points to null , it simply means that there is no value associated with it .

Technically speaking, the memory location assigned to the reference contains the value 0 (all bits at zero), or any other value that denotes null in the given environment.

Performance

As we learned in the previous section, operations involving null are extremely fast and easy to perform at run-time.

There are only two kinds of operations:

  • Initialize or set a reference to null (e.g. name = null ): The only thing to do is to change the content of one memory cell (e.g. setting it to 0).
  • Check if a reference points to null (e.g. if name == null ): The only thing to do is to check if the memory cell of the reference holds the value 0.

Operations on null are exceedingly fast and cheap.

Reference vs Value Types

So far we assumed working with reference types . The reason for this is simple: null doesn't exist for value types .

As we have seen previously, a reference is a pointer to a memory-address that stores a value (e.g. a string, a date, a customer, whatever). If a reference points to null , then no value is associated with it.

On the other hand, a value is, by definition, the value itself. There is no pointer involved. A value type is stored as the value itself. Therefore the concept of null doesn't exist for value types.

The following picture demonstrates the difference. On the left side you can see again the memory in case of variable name being a reference pointing to "Bob". The right side shows the memory in case of variable name being a value type.

Image

As we can see, in case of a value type, the value itself is directly stored at the address A0A1 which is associated with variable name .

There would be much more to say about reference versus value types, but this is out of the scope of this article. Please note also that some programming languages support only reference types, others support only value types, and some (e.g. C# and Java) support both of them.

The concept of null exists only for reference types. It doesn't exist for value types .

Suppose we have a type person with a field emailAddress . Suppose also that, for a given person which we will call Alice, emailAddress points to null .

What does this mean? Does it mean that Alice doesn’t have an email address? Not necessarily.

As we have seen already, what we can assert is that no value is associated with emailAddress .

But why is there no value? What is the reason of emailAddress pointing to null ? If we don't know the context and history, then we can only speculate. The reason for null could be:

Alice doesn’t have an email address. Or…

Alice has an email address, but:

  • it has not yet been entered in the database
  • it is secret (unrevealed for security reasons)
  • there is a bug in a routine that creates a person object without setting field emailAddress

In practice we often know the application and context. We intuitively associate a precise meaning to null . In a simple and flawless world, null would simply mean that Alice actually doesn't have an email address.

When we write code, the reason why a reference points to null is often irrelevant. We just check for null and take appropriate actions. For example, suppose that we have to write a loop that sends emails for a list of persons. The code (in Java) could look like this:

In the above loop we don’t care about the reason for null . We just acknowledge the fact that there is no email address, log a warning, and continue.

If a reference points to null then it always means that there is no value associated with it .

In most cases, null has a more specific meaning that depends on the context .

Why is it null ?

Sometimes it is important to know why a reference points to null .

Consider the following function signature in a medical application:

In this case, returning null (or an empty list) is ambiguous. Does it mean that the patient doesn't have allergies, or does it mean that an allergy test has not yet been performed? These are two semantically very different cases that must be handled differently. Or else the outcome might be life-threatening.

Just suppose that the patient has allergies, but an allergy test has not yet been done and the software tells the doctor that 'there are no allergies'. Hence we need additional information. We need to know why the function returns null .

It would be tempting to say: Well, to differentiate, we return null if an allergy test has not yet been performed, and we return an empty list if there are no allergies.

DON’T DO THIS!

This is bad data design for multiple reasons.

The different semantics for returning null versus returning an empty list would need to be well documented. And as we all know, comments can be wrong (i.e. inconsistent with the code), outdated, or they might even be inaccessible.

There is no protection for misuses in client code that calls the function. For example, the following code is wrong, but it compiles without errors. Moreover, the error is difficult to spot for a human reader. We can’t see the error by just looking at the code without considering the comment of getAllergiesOfPatient:

The following code would be wrong too:

If the null /empty-logic of getAllergiesOfPatient changes in the future, then the comment needs to be updated, as well as all client code. And there is no protection against forgetting any one of these changes.

If, later on, there is another case to be distinguished (e.g. an allergy test is pending — the results are not yet available), or if we want to add specific data for each case, then we are stuck.

So the function needs to return more information than just a list.

There are different ways to do this, depending on the programming language we use. Let’s have a look at a possible solution in Java.

In order to differentiate the cases, we define a parent type AllergyTestResult , as well as three sub-types that represent the three cases ( NotDone , Pending , and Done ):

As we can see, for each case we can have specific data associated with it.

Instead of simply returning a list, getAllergiesOfPatient now returns an AllergyTestResult object:

Client code is now less error-prone and looks like this:

Note: If you think that the above code is quite verbose and a bit hard to write, then you are not alone. Some modern languages allow us to write conceptually similar code much more succinctly. And null-safe languages distinguish between nullable and non-nullable values in a reliable way at compile-time — there is no need to comment the nullability of a reference or to check whether a reference declared to be non-null has accidentally been set to null .

If we need to know why there is no value associated with a reference, then additional data must be provided to differentiate the possible cases .

Initialization

Consider the following instructions:

The first instruction declares a String variable s1 and assigns it the value "foo" .

The second instruction assigns null to s2 .

The more interesting instruction is the last one. No value is explicitly assigned to s3 . Hence, it is reasonable to ask: What is the state of s3 after its declaration? What will happen if we write s3 to the OS output device?

It turns out that the state of a variable (or class field) declared without assigning a value depends on the programming language. Moreover, each programming language might have specific rules for different cases. For example, different rules apply for reference types and value types, static and non-static members of a class, global and local variables, and so on.

As far as I know, the following rules are typical variations encountered:

  • It is illegal to declare a variable without also assigning a value
  • There is an arbitrary value stored in s3 , depending on the memory content at the time of execution - there is no default value
  • A default value is automatically assigned to s3. In case of a reference type, the default value is null. In case of a value type, the default value depends on the variable’s type. For example 0 for integer numbers, false for a boolean, and so on.
  • the state of s3 is 'undefined'
  • the state of s3 is 'uninitialized', and any attempt to use s3 results in a compile-time error.

The best option is the last one. All other options are error-prone and/or impractical — for reasons we will not discuss here, because this article focuses on null .

As an example, Java applies the last option for local variables. Hence, the following code results in a compile-time error at the second line:

Compiler output:

If a variable is declared, but no explicit value is assigned to it, then it’s state depends on several factors which are different in different programming languages.

In some languages, null is the default value for reference types.

When to Use null (And When Not to Use It)

The basic rule is simple: null should only be allowed when it makes sense for an object reference to have 'no value associated with it'. (Note: an object reference can be a variable, constant, property (class field), input/output argument, and so on.)

For example, suppose type person with fields name and dateOfFirstMarriage :

Every person has a name. Hence it doesn’t make sense for field name to have 'no value associated with it'. Field name is non-nullable . It is illegal to assign null to it.

On the other hand, field dateOfFirstMarriage doesn't represent a required value. Not everyone is married. Hence it makes sense for dateOfFirstMarriage to have 'no value associated with it'. Therefore dateOfFirstMarriage is a nullable field. If a person's dateOfFirstMarriage field points to null then it simply means that this person has never been married.

Note: Unfortunately most popular programming languages don’t distinguish between nullable and non-nullable types. There is no way to reliably state that null can never be assigned to a given object reference. In some languages it is possible to use annotations, such as the non-standard annotations @Nullable and @NonNullable in Java. Here is an example:

However, such annotations are not used by the compiler to ensure null-safety. Still, they are useful for the human reader, and they can be used by IDEs and tools such as static code analyzers.

It is important to note that null should not be used to denote error conditions.

Consider a function that reads configuration data from a file. If the file doesn’t exist or is empty, then a default configuration should be returned. Here is the function’s signature:

What should happen in case of a file read error?

Simply return null ?

Each language has it’s own standard way to signal error conditions and provide data about the error, such as a description, type, stack trace, and so on. Many languages (C#, Java, etc.) use an exception mechanism, and exceptions should be used in these languages to signal run-time errors. readConfigFromFile should not return null to denote an error. Instead, the function's signature should be changed in order to make it clear that the function might fail:

  • Allow null only if it makes sense for an object reference to have 'no value associated with it'.
  • Don’t use null to signal error conditions.

Null-safety

Consider the following code:

At run-time, the above code results in the infamous null pointer error , because we try to execute a method of a reference that points to null . In C#, for example, a NullReferenceException is thrown, in Java it is a NullPointerException .

The null pointer error is nasty.

It is the most frequent bug in many software applications, and has been the cause for countless troubles in the history of software development. Tony Hoare, the inventor of null , calls it the 'billion-dollar mistake'.

But Tony Hoare (Turing Award winner in 1980 and inventor of the Quicksort algorithm), also gives a hint to a solution in his speech :

More recent programming languages … have introduced declarations for non-null references. This is the solution, which I rejected in 1965.

Contrary to some common belief, the culprit is not null per se. The problem is the lack of support for null handling in many programming languages. For example, at the time of writing (May 2018), none of the top ten languages in the Tiobe index natively differentiates between nullable and non-nullable types.

Therefore, some new languages provide compile-time null-safety and specific syntax for conveniently handling null in source code. In these languages, the above code would result in a compile-time error. Software quality and reliability increases considerably, because the null pointer error delightfully disappears.

Null-safety is a fascinating topic that deserves its own article.

Whenever possible, use a language that supports compile-time null-safety.

Note: Some programming languages (mostly functional programming languages like Haskell) don’t support the concept of null . Instead, they use the Maybe/Optional Pattern to represent the ‘absence of a value’. The compiler ensures that the ‘no value’ case is handled explicitly. Hence, null pointer errors cannot occur.

Here is a summary of key points to remember:

  • If a reference points to null , it always means that there is no value associated with it .
  • In most cases, null has a more specific meaning that depends on the context.
  • If we need to know why there is no value associated with a reference, then additional data must be provided to differentiate the possible cases.
  • The concept of null exists only for reference types. It doesn't exist for value types.
  • In some languages null is the default value for reference types.
  • null operations are exceedingly fast and cheap.
  • Whenever possible, use a language that supports compile-time-null-safety.

Learn to code. Build projects. Earn certifications—All for free.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Javatpoint Logo

  • Design Pattern
  • Interview Q

C Control Statements

C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.

JavaTpoint

A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the segment. The null pointer basically stores the Null value while void is the type of the pointer.

A null pointer is a special reserved value which is defined in a header file. Here, Null means that the pointer is referring to the 0 memory location.

If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When a NULL value is assigned to the pointer, then it is considered as a .

In the above code, we declare the pointer variable *ptr, but it does not contain the address of any variable. The dereferencing of the uninitialized pointer variable will show the compile-time error as it does not point any variable. According to the stack memory concept, the local variables of a function are stored in the stack, and if the variable does not contain any value, then it shows the garbage value. The above program shows some unpredictable results and causes the program to crash. Therefore, we can say that keeping an uninitialized pointer in a program can cause serious harm to the computer.

We can avoid the above situation by using the Null pointer. A null pointer is a pointer pointing to the 0 memory location, which is a reserved memory and cannot be dereferenced.

In the above code, we create a pointer and assigns a value to the pointer, which means that it does not point any variable. After creating a pointer variable, we add the condition in which we check whether the value of a pointer is null or not.

In the above code, we use the library function, i.e., . As we know, that malloc() function allocates the memory; if malloc() function is not able to allocate the memory, then it returns the pointer. Therefore, it is necessary to add the condition which will check whether the value of a pointer is null or not, if the value of a pointer is not null means that the .

There are various uses of NULL Pointer in C. Some main uses of NULL Pointer are as follows:

are used to initialize pointers when there is no suitable memory address to designate as the starting address. A pointer is prevented from unintentionally pointing to random or incorrect memory by being set to . By doing this, possible crashes and unauthorized memory access are avoided.

The handling of errors with pointers depends heavily on . It is crucial to determine whether a reference is a NULL reference before dereferencing it. may result in or . As a result, adding an to check that the pointer is not helps prevent such problems and ensures the dependability of the program.

In C, methods like , and are used to implement . These routines return a if memory allocation fails owing to inadequate memory or another issue. After dynamic memory allocation, it is crucial to check for a to see if the memory allocation was successful or not.

are frequently utilized as function return values and values. are used to denote the absence of a valid reference when a function does not need to or a valid memory address. This procedure aids in the clear expression of intent and helps to prevent function use ambiguity.

Occasionally, some pointers are not intended for use in a particular situation or area of the code. We make sure they don't unintentionally point to legitimate memory addresses inside that scope by changing them to , avoiding unauthorized data tampering.

act as the end marker in data structures like linked lists. A linked list's last node, which refers to NULL, denotes the list's conclusion. It makes it possible to efficiently traverse the list and makes it easier to identify the list's termination point.

A refers to a memory address that has previously been or released. To prevent dangling pointers, assign to a pointer after releasing the memory it refers to. are safe operations that guard against potential issues brought on by the use of dangling pointers.

C libraries and employ . The use of to denote optional or missing arguments when communicating with other libraries or systems results in code that is clearer and easier to comprehend.

In conclusion, are an essential component of C programming and play a key role in assuring the , , and resilience of the code. NULL Pointers are used to represent pointers that do not point to any legitimate memory addresses, thereby reducing the likelihood of crashes and other unexpected behavior. It is crucial to initialize pointers with NULL at the time of declaration and verify for before dereferencing them to prevent such hazards.

The , and are additional areas where NULL Pointers are quite useful. They offer a short and unambiguous approach to express the lack of valid data or memory locations in a variety of circumstances. Programmers may create more reliable and predictable C programs by sparingly using , which reduces the risk of problems and improves the overall quality of their code. Working with pointers in C requires constant attention to since they help to produce more dependable and secure applications.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What exactly is meant by "de-referencing a NULL pointer"?

I am a complete novice to C, and during my university work I've come across comments in code that often refer to de-referencing a NULL pointer. I do have a background in C#, I've been getting by that this might be similar to a "NullReferenceException" that you get in .Net, but now I am having serious doubts.

Can someone please explain to me in layman's terms exactly what this is and why it is bad?

cigien's user avatar

  • 1 Keep in mind doing so results in undefined behavior. You don't get exceptions or anything, in C or C++. –  GManNickG Commented Oct 24, 2010 at 7:09
  • 1 You might want to put down some example code. It seems that people (including me) don't get what you are trying to ask. –  user168237 Commented Oct 24, 2010 at 7:24
  • 3 No need for code (there isn't any) - This is a conceptual problem I am having, trying to get my head around the terminology of "dereferencing" and why I should be caring about it. –  Ash Commented Oct 26, 2010 at 4:22
  • 7 youtube.com/watch?v=bLHL75H_VEM –  Veer Singh Commented Jan 7, 2016 at 2:16

9 Answers 9

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

Greg Hewgill's user avatar

  • 21 @Ash: A pointer contains a memory address that references to something. To access that something referenced by that memory address, you have to de-reference the memory address. –  In silico Commented Oct 24, 2010 at 5:14
  • 1 @Ash, which In silico said, but when you de-reference you getting the value that is stored at the memory address. Give it a try. Do int p; printf("%p\n", &p); it should print out an address. When you don't create a pointer (*var), to get the address you use &var –  Matt Commented Oct 24, 2010 at 16:21
  • 1 @Greg How about when you do char *foo = NULL and then use &foo ? –  Bionix1441 Commented Feb 22, 2017 at 9:45
  • 1 @Bionix1441: In your example &foo refers to the address of the variable called foo , which is fine given its declaration. –  Greg Hewgill Commented Feb 22, 2017 at 16:55
  • 1 I think it's important to also state that it's undefined behavior, assuming that Adam Rosenfield's answer is correct. –  axel22 Commented Jan 26, 2020 at 17:22

Dereferencing just means accessing the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.

In C, the unary * operator is the dereferencing operator. If x is a pointer, then *x is what x points to. The unary & operator is the address-of operator. If x is anything, then &x is the address at which x is stored in memory. The * and & operators are inverses of each other: if x is any data, and y is any pointer, then these equations are always true:

A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).

In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:

And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException in C# (or a NullPointerException in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException . There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).

fwr nr's user avatar

  • 4 Actually, a NULL pointer does sometimes point to valid data. Many microcontrollers implement flash/peripherals at the address 0. –  Sapphire_Brick Commented Jul 19, 2020 at 6:10

basically, almost anything involving (*p) or implicitly involving (*p) , e.g. p->... which is a shorthand for (*p). ... ; except for pointer declaration.

Lie Ryan's user avatar

  • 1 He tagged his question as C not C++ –  GWW Commented Oct 24, 2010 at 5:13
  • 3 @GWW: and it has exactly the same semantic in C and in C++, except perhaps C does not have costum class. –  Lie Ryan Commented Oct 24, 2010 at 5:16
  • 2 Isn't p->meth() just a shorthand for (*p).meth() , with the latter being available in both C and C++? –  Arun Commented Oct 24, 2010 at 7:12
  • 1 @Arun Both of those are legal in both C and C++. –  Sapphire_Brick Commented Jul 19, 2020 at 6:13
A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object .. Since a null-valued pointer does not refer to a meaningful object, an attempt to dereference a null pointer usually causes a run-time error.

Prasoon Saurav's user avatar

  • 1 Thanks for your answer, I am ok with what a NULL pointer was, I just wasn't sure about how the "dereferencing" fits into the scheme of things. –  Ash Commented Oct 24, 2010 at 5:15
  • 8 I didn't know that program crashes go " Whooosh!!!! ". –  Sapphire_Brick Commented Jul 19, 2020 at 6:14

Quoting from wikipedia :

A pointer references a location in memory, and obtaining the value at the location a pointer refers to is known as dereferencing the pointer.

Dereferencing is done by applying the unary * operator on the pointer.

"Dereferencing a NULL pointer" means performing *p when the p is NULL

Arun's user avatar

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault . There's an easier way to de-reference a NULL pointer, take a look.

Since 0 is never a valid pointer value, a fault occurs.

vmemmap's user avatar

  • (int *)0 is not strictly speaking a null pointer constant, so this code could just as well be application code writing to address zero, not to be confused with null pointers. There is nothing in your example formally guaranteeing a null-pointer access nor a seg fault. In order to create a null pointer, you need to assign a null pointer constant to a pointer. Null pointer constant being either 0 or (void*)0 . The NULL macro can be either of these. –  Lundin Commented May 11, 2022 at 9:47
  • @Lundin - IIRC, (void *)0 is a valid null pointer constant, so it's not differ than (int *)0 . The code assigns a zero value to an integer pointer then dereferences it. –  vmemmap Commented Jun 24, 2022 at 10:28
  • 1 (void *)0 is a valid null pointer constant because the standard explicitly says so. It says nothing about (int*)0 . –  Lundin Commented Jun 27, 2022 at 9:06

Lots of confusion and confused answers here. First of all, there is strictly speaking nothing called a "NULL pointer". There are null pointers, null pointer constants and the NULL macro.

Start by studying my answer from Codidact: What's the difference between null pointers and NULL? Quoting some parts of it here:

There are three different, related concepts that are easy to mix up: null pointers null pointer constants the NULL macro Formal definitions The first two of these terms are formally defined in C17 6.3.2.3/3: An integer constant expression with the value 0 , or such an expression cast to type void * , is called a null pointer constant . 67) 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.

In other words, a null pointer is a pointer of any type pointing at a well-defined "nowhere". Any pointer can turn into a null pointer when it is assigned a null pointer constant.

The standard mentions 0 and (void*)0 as two valid null pointer constants, but note that it says "an integer constant expression with the value 0 ". This means that things like 0u , 0x00 and other variations are also null pointer constants. These are particular special cases that can be assigned to any pointer type, regardless of the various type compatibility rules that would normally apply.

Notably, both object pointers and function pointers can be null pointers. Meaning that we must be able to assign null pointer constants to them, no matter the actual pointer type.

The note 67) from above adds (not normative):

67) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19.

where 7.19 simply defines NULL as (normative):

NULL which expands to an implementation-defined null pointer constant;

In theory this could perhaps be something other than 0 and (void*)0 , but the implementation-defined part is more likely saying that NULL can either be #define NULL 0 or #define NULL (void*)0 or some other integer constant expression with the value zero, depending on the C library used. But all we need to know and care about is that NULL is a null pointer constant.

NULL is also the preferred null pointer constant to use in C code, because it is self-documenting and unambiguous (unlike 0 ). It should only be used together with pointers and not for any other purpose.

Additionally, do not mix this up with "null termination of strings", which is an entirely separate topic. Null termination of strings is just a value zero, often referred to either as nul (one L) or '\0' (an octal escape sequence), just to separate it from null pointers and NULL .

Dereferencing

Having cleared that out, we cannot access what a null pointer points at, because it is as mentioned a well-defined "nowhere". The process of accessing what a pointer points at is known as dereferencing , and is done in C (and C++) through the unary * indirection operator. The C standard specifying how this operator works simply states (C17 6.5.3.3):

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined

Where an informative note adds:

Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.

And this would be where "segmentation faults" or "null pointer/reference exceptions" might be thrown. The reason for such is almost always an application bug such as these examples:

Lundin's user avatar

  • In some cases, it's not quite clear whether an expression "dereferences" a pointer. For example, an expression like (uintptr_t)&(structPtr->member) could be evaluated without performing any access to the pointer in question, and even if an implementation that would usefully trap pointer arithmetic involving null pointers in most contexts, it could recognize that an expression like the above is ultimately forming an integer rather than a pointer. –  supercat Commented May 23, 2022 at 15:06

Let's look at an example of dereferencing a NULL pointer, and talk about it.

Here is an example of dereferencing a NULL pointer, from this duplicate question here: uint32_t *ptr = NULL; :

Memory hasn't been allocated for the uint32_t , so calling *ptr , which "dereferences" the pointer, ptr , or otherwise said: accesses memory at an unallocated ( NULL --usually 0 , but implementation-defined) address, is illegal. It is "undefined behavior"--ie: a bug.

So, you should statically (preferred, where possible), or dynamically allocate space for a uint32_t and then only dereference a pointer which points to valid memory, as follows.

Here is how to statically allocate memory and use it with a pointer. Note even that the memory for the pointer itself is statically allocated in my example!:

Note, dynamic allocation is fine too, but static memory allocation is safer, deterministic, faster, better for memory-constrained embedded systems, blah blah blah. The point is simply that you cannot legally dereference any pointer (meaning: put an asterisk "dereference operator" in front of it, like *ptr ) which does not point to a chunk of allocated memory. I generally allocate memory statically by declaring a variable.

Gabriel Staples's user avatar

A null pointer is basically a pointer which points to no object in the memory.

Dereferencing a pointer means trying to access object at the pointer's memory address.(Pointer is a reference and trying to de- reference means you are trying to get the actual object it points to ).

When you try to dereference a null pointer it means you are trying to address an object that isn't there . This leads to undefined behaviour .

Kushagra Sharma's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c pointers or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Is this map real?
  • What prevents random software installation popups from mis-interpreting our consents
  • Unstable plans when two first index columns have NULL values in all rows
  • How much technological progress could a group of modern people make in a century?
  • Could they free up a docking port on ISS by undocking the emergency vehicle and letting it float next to the station for a little while
  • Are there epistemic vices?
  • How can I power 28VDC devices from a 24VDC system?
  • I want to be a observational astronomer, but have no idea where to start
  • Looking for the name of a possibly fictional science fiction TV show
  • Syntactically, who does Jesus refer to as 'to you' and 'those outside' in Mark 4:11?
  • How to truncate text in latex?
  • Does this policy mean that my work has flawed password storage?
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • Inertia Action on Kummer Sheaves
  • Did Queen (or Freddie Mercury) really not like Star Wars?
  • Advanced Composite Solar Sail (ACS3) Orbit
  • How much could gravity increase before a military tank is crushed
  • Model reduction in linear regression by stepwise elimination of predictors with "non-significant" coefficients
  • Can a V22 Osprey operate with only one propeller?
  • How cheap would rocket fuel have to be to make Mars colonization feasible (according to Musk)?
  • Analog story - US provides food machines to other nations, with hidden feature
  • When a mass crosses a black hole event horizon does the horizon radius get larger closer to the mass or does it increase equally everywhere?
  • Why does my LED bulb light up dimly when I touch it?
  • Is the white man at the other side of the Joliba river a historically identifiable person?

explain null pointer assignment

IMAGES

  1. NULL Pointer in C example or What is NULL Pointer in C

    explain null pointer assignment

  2. Understanding the Null Pointers

    explain null pointer assignment

  3. NULL Pointer in C with example

    explain null pointer assignment

  4. Null Pointer in C Language with Examples

    explain null pointer assignment

  5. Null pointer in C

    explain null pointer assignment

  6. NULL pointer in C

    explain null pointer assignment

VIDEO

  1. What are Pointers? How to Use Them? and How they can Improve your C++ Programming Skills

  2. What is a C++ null pointer? ⛔

  3. Null Pointer Exception Song #2

  4. Wild Pointer & Null Pointer in C Language #cprogramming #ccode #computerlanguage

  5. Built in Exception and Null Pointer Exception || Salesforce Apex for Beginners

  6. Pointers in C

COMMENTS

  1. c

    A null pointer assignment error, or many other errors, can be assigned to this issue and example. In simpler architecture or programming environments, It can refer to any code which unintentionally ends up creating nulls as pointers, or creates a bug that in anyway halts the execution, like overwriting a byte in the return stack, overwriting ...

  2. NULL Pointer in C

    NULL Pointer in C

  3. 12.8

    12.8 — Null pointers. Alex January 10, 2024. In the previous lesson (12.7 -- Introduction to pointers), we covered the basics of pointers, which are objects that hold the address of another object. This address can be dereferenced using the dereference operator (*) to get the object at that address: #include <iostream> int main() { int x { 5 };

  4. How C-Pointers Works: A Step-by-Step Beginner's Tutorial

    NULL Pointers. A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers. Here's a code example that demonstrates the use of a NULL pointer:

  5. Dangling, Void , Null and Wild Pointers in C

    Dangling, Void , Null and Wild Pointers in C

  6. NULL Pointer in C

    NULL Pointer in C. A NULL pointer in C is a pointer that doesn't point to any of the memory locations. The NULL constant is defined in the header files stdio.h, stddef.h as well as stdlib.h. A pointer is initialized to NULL to avoid the unpredicted behavior of a program or to prevent segmentation fault errors.

  7. NULL implementation and pointer assignment

    1. NULL should not be used to refer to a null character; it's a null pointer constant. C implementations can define NULL either as ((void*)0) the outer parentheses are necessary) or as 0, or in any of several other forms. C++, which is a different language, has different requirements for null pointer constants, and C++ implementations commonly ...

  8. Null pointer in C

    Null pointer in C | How Null pointer work in C with Examples

  9. C++ Null Pointers

    C++ Null Pointers

  10. C++ Null Pointers with examples

    NULL is itself a special type of pointer. When we initialize a pointer with NULL then that pointer also becomes a NULL pointer. Example to understand what is a NULL pointer. #include <iostream>. using namespace std; int main() {. int *ptr = NULL; // This is a NULL pointer. return 0;

  11. NULL Pointer in C++

    NULL Pointer in C++

  12. Learn What A Null Pointer Constant (nullptr) Is In Modern C++

    The nullptr keyword is a null pointer constant which is a prvalue of type std::nullptr_t. that denotes the pointer literal. C++11 introduced nullptr, the null pointer constant, to remove the ambiguity between 0 and a null pointer. Although the old style NULL macro exists, it is insufficient because it cannot be distinguished from the integer 0 ...

  13. NULL Pointer in C with example

    C language Pointer Tutorial...! 👇👇👇https://www.youtube.com/playlist?list=PLqleLpAMfxGC_39XKLj10U_k_n2_V2VEmPlease Subscribe our Channel...!Learn Coding 🙏...

  14. Using Null Pointer in Programs in C

    Using Null Pointer Program. NULL is a macro in C, defined in the <stdio.h> header file, and it represent a null pointer constant. Conceptually, when a pointer has that Null value it is not pointing anywhere. If you declare a pointer in C, and don't assign it a value, it will be assigned a garbage value by the C compiler, and that can lead to ...

  15. 3 Major use of NULL Pointer in C Programming

    The NULL constant is defined in many of the header files in the C programming language; including, stdio.h stddef.h, stdlib.h, etc. In C programming, usually, we add stdio.h in the program to use scanf() and printf() functions. So, you don't need to add any extra header files. Later in the code, you can assign any memory location to ptr pointer.

  16. Null Pointer Exception In Java

    Null Pointer Exception In Java

  17. A quick and thorough guide to 'null': what it is, and how you should use it

    A quick and thorough guide to 'null': what it is, and how you ...

  18. Null Pointer in C

    Null Pointer in C

  19. C

    The NULL pointer is a constant with a value of zero defined in several standard libraries. But the pointer variable can be changed, proof: #include <stdio.h>. int main() {. int *a = NULL; /* Declaration\Definition of pointer and initialization of NULL */. int b; /* Regular Declaration\Definition of variable */.

  20. How to assign a value to a pointer that points to NULL

    A pointer can't point to null. It can be a null pointer, which means it doesn't point to anything. And a declared object can't be deleted as long as its name is visible; it only ceases to exist at the end of its scope. &value is a valid address at the time the assignment nullPointer = &value; is executed. It might become invalid later.

  21. What exactly is meant by "de-referencing a NULL pointer"?

    What exactly is meant by "de-referencing a NULL pointer"?