Dangling Pointer in C


A dangling pointer is a pointer that points to a memory location that is no longer valid. This can occur when a memory block is dynamically allocated and then subsequently freed, but the pointer to that memory block is not set to NULL or is not properly updated to point to a different valid memory location. Attempting to access the memory through the dangling pointer can lead to undefined behavior, such as a program crash or unexpected results.

  • This program demonstrates an example of a "dangling pointer." When the function "value()" is called, it creates a local variable "a" and assigns it the value 10.
  • It then returns the address of this variable, which is stored in the pointer "ptr."
  • However, since "a" is a local variable of the function "value()," it goes out of scope and its memory is freed once the function returns.
  • Therefore, the pointer "ptr" now points to a location in memory that is no longer valid, making it a "dangling pointer."
  • This can lead to undefined behavior and potential errors in the program if the pointer is dereferenced and used.

Source Code

//Dangling Pointer
#include<stdio.h>
#include<stdlib.h>
 
int * value()
{
    int a=10;
    return &a;
}
 
int main()
{
    int *ptr=NULL;
    ptr=value(); //&a
    printf("%d",*ptr);
    return 0;
}
 
 
 
To download raw file Click Here

Output

returned -1073741819

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C