Dangling Pointer in C Language
×

Dangling Pointer in C Language

71

The pointer points to a memory location that is valid but has been deallocated by the user is called a Dangling pointer.

  Accessing memory through such a pointer can lead to crashes.

dangling pointer in C causes memory leakage.

 This pointer allows you to access and work with the dynamically allocated memory within your program.

If you then deallocate or free that memory using free(), but still keep a pointer pointing to that memory location.

Then that pointer becomes a dangling pointer.

Explanation of dangling pointer in C 

 Initially, we have a memory block allocated dynamically.

Later on, the memory block is deallocated or freed, meaning it's no longer reserved for our program's use.

However, a pointer that was pointing to that memory block still exists in our program.

This pointer is now considered a dangling pointer because it's pointing to memory that has been deallocated.

Accessing or dereferencing this dangling pointer can lead to unexpected behavior or program crashes, as the memory it points to may be reused by the system for other purposes.

Syntax of Dangling pointer 

dataType *p = (dataType *)malloc(sizeof(dataType));
free(p);
Example:

 // Program of dangling pointer
#include <stdio.h>
#include <stdlib.h>
int main() {

int *p = (int *)malloc(sizeof(int));
*p = 10;
printf("Value: %d\n", *p);
free(p);

printf("Value: %d\n", *p);

return 0;
}
Output:

value = 10
value = 0


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments