C NULL

๐Ÿ”น C NULL

NULL is a special constant in C used to represent a null pointer, meaning the pointer does not point to any valid memory location.

It is defined in multiple header files such as:

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

โœ… What is NULL?

NULL stands for “no value” or “empty pointer”.

Example:

int *ptr = NULL;

This means ptr is declared but doesn’t point to any memory address.


๐Ÿง  Why Use NULL?

NULL helps avoid:

  • Dangling pointers

  • Invalid memory access

  • Unpredictable program crashes

Using NULL makes it easy to test whether a pointer has a valid address.


๐Ÿ“Œ Checking NULL Pointer

int *ptr = NULL;

if (ptr == NULL) {
printf("Pointer is NULL.\n");
} else {
printf("Pointer is not NULL.\n");
}


๐Ÿงช Example With Dynamic Memory

#include <stdio.h>
#include <stdlib.h>

int main() {
int *p = malloc(sizeof(int));

if (p != NULL) {
*p = 50;
printf("Value: %d\n", *p);
}

free(p);
p = NULL; // Best practice

if (p == NULL) {
printf("Pointer is now NULL.\n");
}

return 0;
}

๐Ÿ’ก After freeing memory, setting pointer to NULL prevents accidental reuse.


๐Ÿ”ฅ NULL vs Uninitialized Pointer

Pointer State Example Safe?
NULL pointer int *p = NULL; โœ” Safe to check
Uninitialized pointer int *p; โŒ Dangerous

Uninitialized pointers hold garbage values, which may point to invalid or system memory.


๐Ÿšจ Don’t Dereference a NULL Pointer

int *ptr = NULL;
printf("%d", *ptr); // โŒ runtime error

This causes a segmentation fault.


โœ” NULL vs 0

In C, NULL is often defined as:

#define NULL 0

But semantically:

  • 0 is an integer

  • NULL is a pointer constant

So use NULL for pointers:

int *p = NULL; // correct
int *p = 0; // works, but not recommended

๐Ÿ Summary

Concept Meaning
NULL Special value indicating no valid address
Used with Pointers
Common use Checking valid memory before access
Prevents Crashes and undefined behavior

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

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