Dangling Pointers in C

In C programming, a dangling pointer is a pointer that points to a memory location that has been deallocated or freed. It can also occur when a pointer is uninitialized or points to an invalid memory address.

Dangling pointers can lead to undefined behavior, which means that the program’s behavior becomes unpredictable. When a dangling pointer is dereferenced (accessed), it may result in a crash, data corruption, or other unexpected outcomes.

Here are a few common scenarios that can lead to dangling pointers:

  1. Deallocating memory and not updating the pointer: If you deallocate memory using the free() function or delete operator but fail to set the pointer to NULL or assign it a valid memory address, the pointer becomes a dangling pointer. Any attempt to dereference this pointer later will result in undefined behavior.


int* ptr = (int*)malloc(sizeof(int));
free(ptr); // Memory deallocated, but pointer still points to the same address
*ptr = 10; // Dangling pointer, accessing freed memory

2. Returning a pointer to a local variable: When a function returns, its local variables are typically deallocated. If a function returns a pointer to a local variable or a dynamically allocated memory block within the function, it creates a dangling pointer.


int* createArray(int size) {
  int arr[size]; // Local variable
  return arr;    // Dangling pointer, returning the address of a local variable

int* ptr = createArray(5);

3. Using pointers to objects that are destroyed: If you have pointers to objects (e.g., structures or classes) and those objects are destroyed or their memory is deallocated, the pointers become dangling pointers.


struct Person {
  char* name;
  int age;

struct Person* createPerson() {
  struct Person p;
  p.name = "John";
  p.age = 25;
  return &p; // Dangling pointer, returning the address of a local struct

struct Person* ptr = createPerson();

To avoid dangling pointers, it’s important to follow these best practices:

  • When deallocating memory, set the pointer to NULL or assign it a valid address.
  • Avoid returning pointers to local variables or dynamically allocated memory that will be deallocated.
  • Be cautious when using pointers to objects to ensure they remain valid throughout their usage.

By being mindful of these practices, you can minimize the chances of encountering dangling pointers and the associated undefined behavior in your C programs.