Open In App

Dangling, Void , Null and Wild Pointers in C

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deallocated memory), Void (pointing to some data location that doesn’t have any specific type), Null (absence of a valid address), and Wild (uninitialized) pointers.

Dangling Pointer in C

A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs in C programs.

There are three different ways where a pointer acts as a dangling pointer:

1. De-allocation of Memory

When a memory pointed by a pointer is deallocated the pointer becomes a dangling pointer.

Example

The below program demonstrates the deallocation of a memory pointed by ptr.

C




// C program to demonstrate Deallocating a memory pointed by
// ptr causes dangling pointer
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int* ptr = (int*)malloc(sizeof(int));
 
    // After below free call, ptr becomes a dangling pointer
    free(ptr);
    printf("Memory freed\n");
 
    // removing Dangling Pointer
    ptr = NULL;
 
    return 0;
}


Output

Memory freed

2. Function Call 

When the local variable is not static and the function returns a pointer to that local variable. The pointer pointing to the local variable becomes dangling pointer.

Example

The below example demonstrates a dangling pointer when the local variable is not static.

C




// C program to demonstrate the pointer pointing to local
// variable becomes dangling when local variable is not
// static.
#include <stdio.h>
 
int* fun()
{
    // x is local variable and goes out of
    // scope after an execution of fun() is
    // over.
    int x = 5;
 
    return &x;
}
 
// Driver Code
int main()
{
    int* p = fun();
    fflush(stdin);
 
    // p points to something which is not
    // valid anymore
    printf("%d", *p);
    return 0;
}


Output

0

In the above example, p becomes dangling as the local variable (x) is destroyed as soon as the value is returned by the pointer. This can be solved by declaring the variable x as a static variable as shown in the below example.

C




// The pointer pointing to local variable doesn't
// become dangling when local variable is static.
#include <stdio.h>
 
int* fun()
{
    // x now has scope throughout the program
    static int x = 5;
 
    return &x;
}
 
int main()
{
    int* p = fun();
    fflush(stdin);
 
    // Not a dangling pointer as it points
    // to static variable.
    printf("%d", *p);
}


Output

5

3. Variable Goes Out of Scope

When a variable goes out of scope the pointer pointing to that variable becomes a dangling pointer.

Example

C




// C program to demonstrate dangling pointer when variable
// goes put of scope
#include <stdio.h>
#include <stdlib.h>
 
// driver code
int main()
{
    int* ptr;
    // creating a block
    {
        int a = 10;
        ptr = &a;
    }
 
    // ptr here becomes dangling pointer
    printf("%d", *ptr);
 
    return 0;
}


Output

2355224

Void Pointer in C

Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void refers to the type. Basically, the type of data that it points to can be any. Any pointer type is convertible to a void pointer hence it can point to any value. 

Note: Void pointers cannot be dereferenced. It can however be done using typecasting the void pointer. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.

Syntax

void *ptrName;

Example

The below program shows the use void pointer as it is convertible to any pointer type.

C




// C program to demonstrate the void pointer working
 
#include <stdlib.h>
 
int main()
{
    int x = 4;
    float y = 5.5;
 
    // A void pointer
    void* ptr;
    ptr = &x;
 
    // (int*)ptr - does type casting of void
    // *((int*)ptr) dereferences the typecasted
    // void pointer variable.
    printf("Integer variable is = %d", *((int*)ptr));
 
    // void pointer is now float
    ptr = &y;
    printf("\nFloat variable is = %f", *((float*)ptr));
 
    return 0;
}


Output

Integer variable is = 4
Float variable is = 5.500000

To know more refer to the void pointer article

NULL Pointer in C

NULL Pointer is a pointer that is pointing to nothing(i.e. not pointing to any valid object or memory location). In case, if we don’t have an address to be assigned to a pointer, then we can simply use NULL. NULL is used to represent that there is no valid memory address.

Syntax

datatype *ptrName = NULL;

Example

The below example demonstrates the value of the NULL pointer.

C




// C program to show the value of NULL pointer on printing
#include <stdio.h>
int main()
{
    // Null Pointer
    int* ptr = NULL;
 
    printf("The value of ptr is %p", ptr);
    return 0;
}


Output

The value of ptr is (nil)

Note NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.

NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

Wild pointer in C

A pointer that has not been initialized to anything (not even NULL) is known as a wild pointer. The pointer may be initialized to a non-NULL garbage value that may not be a valid address. 

Syntax

dataType *pointerName;

Example

The below example demonstrates the undefined behavior of the Wild pointer.

C




#include <stdio.h>
 
int main()
{
    int* p; /* wild pointer */
 
    // trying to access the value pointed by a wild pointer
    // is undefined behavior
    // printf("Value pointed by wild pointer: %d\n", *p);
    // //give error
 
    int x = 10;
 
    // Accessing the value pointed by 'p'
    printf("Value pointed by 'p' is: %d\n", *p);
 
    return 0;
}


Output

Segmentation Fault (SIGSEGV)
timeout: the monitored command dumped core
/bin/bash: line 1: 32 Segmentation fault

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.



Previous Article
Next Article

Similar Reads

Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
How does 'void*' differ in C and C++?
C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++ For example, the following is valid in C but not C++: void* ptr; int *i = ptr; // Implicit conversion from void* to int* Similarly, int *j = malloc(sizeof(int) * 5); // Implicit conversion
1 min read
Difference between "int main()" and "int main(void)" in C/C++?
Note: This was true for older versions of C but has been changed in C11 (and newer versions). In newer versions, foo() is same as foo(void). Consider the following two definitions of main(). Definition 1: C/C++ Code int main() { /* */ return 0; } C/C++ Code int main() { /* */ return 0; } Definition 2: C/C++ Code int main(void) { /* */ return 0; } C
3 min read
Is it fine to write void main() or main() in C/C++?
In C/C++ the default return type of the main function is int, i.e. main() will return an integer value by default. The return value of the main tells the status of the execution of the program. The main() function returns 0 after the successful execution of the program otherwise it returns a non-zero value. Using void main in C/C++ is considered no
3 min read
Return From Void Functions in C++
Void functions are known as Non-Value Returning functions. They are "void" due to the fact that they are not supposed to return values. True, but not completely. We cannot return values but there is something we can surely return from void functions. Void functions do not have a return type, but they can do return values. Some of the cases are list
2 min read
void Pointer in C
A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type. Example of Void Pointer in C C/C++ Code // C Program to demonstrate that a void pointer // can hold the address of any type-castable type #include &lt;stdio.h&gt; int main() { int a = 10; char b = '
3 min read
Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Passing Pointers to Functions in C
Prerequisites: Pointers in CFunctions in C Passing the pointers to the function means the memory location of the variables is passed to the parameters in the function, and then the operations are performed. The function definition accepts these addresses using pointers, addresses are stored using pointers. Arguments Passing without pointer When we
2 min read
Output of C programs | Set 64 (Pointers)
Prerequisite : Pointers in C Question 1 : What will be the output of following program? C/C++ Code #include &amp;quot;stdio.h&amp;quot; int main() { char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &amp;amp;a[0]; *ppp++; // Line 1 printf(&amp;quot;%c %c &amp;quot;, *++ppp, --*ppp); // Line 2 } OPTIONS: a)C B b)B A c)B C d)C A OUTPUT: (d) C A Explanat
3 min read
Why Does C Treat Array Parameters as Pointers?
In C, array parameters are treated as pointers mainly to, To increase the efficiency of codeTo save time It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array. The following two definit
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from each other in C++. What is an Array?An array is the
3 min read
Applications of Pointers in C
Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers ApplicationThe following are some major applications o
4 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables that are references to a memory location. It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it. Syntax: pointer_type *array_nam
6 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeGApproach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two p
2 min read
NULL Pointer in C
The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard: “An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guarantee
4 min read
SQL NOT NULL Constraint
Pre-requisite: NULL Values in SQL The SQL NOT NULL forces particular values or records should not to hold a null value. It is somewhat similar to the primary key condition as the primary key can't have null values in the table although both are completely different things. In SQL, constraints are some set of rules that are applied to the data type
2 min read
Passing NULL to printf in C
Consider the following C code snippet. char* p = NULL; printf("%s", p); What should be the output of the above program? The print expects a '\0' terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior. According to Section 7.1.4(of C99 or C11) : Use of library functions If
1 min read