View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Dangling Pointer in C: What, Why & How to Avoid It

Updated on 09/05/20253,552 Views

If you’ve spent any time coding in C, you’ve likely come across the term dangling pointer in C. It sounds harmless—maybe even a little funny—but in reality, it's one of those pesky bugs that can cause unpredictable behavior, memory corruption, crashes, or worse: subtle logical errors that take hours (or days) to trace.

In C, you're given direct access to memory via pointers. This power comes with the risk of using memory incorrectly. A dangling pointer in C is a pointer that continues to reference a memory location after the object it points to has been deleted or deallocated. To understand this more accurately, you should explore dynamic memory allocation in C programming.

In this blog, we’re going to break down exactly what a dangling pointer in C is, how it’s created, and most importantly, how to avoid it. We'll walk through code examples, explain the risks, and offer practical strategies, just like they are provided in top-rated software development courses. So, if you’ve ever scratched your head at a segmentation fault or weird behavior after free(), you’re in the right place.

What are Dangling Pointer in C?

A dangling pointer in C is a pointer that doesn’t point to a valid memory location. It may still hold a memory address, but the data at that address is either invalid or has been reclaimed by the system. Using such pointers can lead to undefined behavior, making your program crash or behave unpredictably.

In simpler terms, a dangling pointer in C is like a house key you kept after the house was demolished—it doesn’t open anything anymore, but it still looks like it should.

Consequences of Using a Dangling Pointer in C

Let’s look at why a dangling pointer in C is dangerous:

  • Crashes: Accessing memory through a dangling pointer in C can cause segmentation faults.
  • Data Corruption: If that memory has been reassigned to another part of the program, you might accidentally overwrite valid data.
  • Unpredictable Behavior: Since memory could be re-used for different purposes, using a dangling pointer in C might not crash immediately—it might just cause strange results.

Unlock a high-paying job with the following full-stack development courses:

Example: Accessing Freed Memory

Let’s look at a basic code snippet that causes a dangling pointer in C.

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

int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocating memory
*ptr = 42; // Assigning value

printf("Value before free: %d\n", *ptr); // Output: 42

free(ptr); // Memory is deallocated

printf("Value after free: %d\n", *ptr); // Undefined behavior! Dangling pointer in use

return 0;
}

Output

Value before free: 42

Value after free: [undefined or garbage value, or crash]

Explanation

In this example, `ptr` initially points to dynamically allocated memory holding the value `42`. After we call `free(ptr);`, the memory is returned to the system. But `ptr` still holds the address. So when we try to access `*ptr`, we’re using a dangling pointer in C—the program might still run, or it might crash, or worse, silently produce garbage.

In short, the object is gone, but the pointer still lingers. That’s the danger.

Additionally, before you move forward the details, it’s recommended to understand the following C concepts:

How the Dangling Pointer in C are Created?

To prevent errors effectively, you first need to understand how they happen. A dangling pointer in C doesn’t just appear out of nowhere—it’s the result of specific coding practices, often subtle ones. Let’s dig deep into the common scenarios that lead to a dangling pointer in C, and understand what exactly goes wrong in each case.

There are three primary ways a dangling pointer in C is typically created:

1. Using Memory After It Has Been Freed (Deallocation of Memory)

This is the most obvious and frequent cause. When you allocate memory dynamically using `malloc()` or `calloc()`, you must eventually free that memory using `free()`. However, if you continue to use the pointer after the memory has been freed, you’re accessing memory you no longer legally own—this is the essence of a dangling pointer in C.

Example: Accessing Freed Memory

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

int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocate memory for an integer
*ptr = 100; // Store a value

printf("Before freeing: %d\n", *ptr); // Valid access

free(ptr); // Memory is now deallocated

// This is now a dangling pointer in C
printf("After freeing: %d\n", *ptr); // Undefined behavior

return 0;
}

Output

Before freeing: 100

After freeing: [could be garbage value or crash]

Explanation

After the `free(ptr)` call, the memory that `ptr` points to has been released back to the system. While `ptr` still holds the address, accessing it is illegal. This results in a dangling pointer in C. The program may still compile and run, but the result is unpredictable—it might crash, produce garbage, or silently corrupt other data.

2. Returning Address of a Local Variable

A subtle yet dangerous way to create a dangling pointer in C is by returning the address of a local (stack-allocated) variable from a function. Stack variables are destroyed automatically once the function returns, so any pointer to them becomes invalid.

Also read, what is variable in C to gain a better insight about local variable.

Example: Returning Local Address

#include <stdio.h>

int* createPointer() {
int local = 42; // Local variable
return &local; // Returning address of a local variable
}

int main() {
int *ptr = createPointer();

// ptr is now a dangling pointer in C
printf("Dangling pointer value: %d\n", *ptr); // Undefined behavior

return 0;
}

Output

Dangling pointer value: [garbage or crash]

Explanation

In this case, the pointer `ptr` receives the address of `local`, which ceases to exist after `createPointer()` returns. So, `ptr` becomes a dangling pointer in C. The memory location might be reused, causing the value at that address to be overwritten by something else—leading to potentially serious bugs.

3. Pointer to a Variable That Goes Out of Scope

Just like returning a local variable's address from a function, you can also create a dangling pointer in C by assigning the address of a scoped variable to a pointer and then using that pointer after the variable’s scope ends.

Example: Out-of-Scope Variable

#include <stdio.h>

int* getScopedPointer() {
int temp = 88; // Scoped variable
int *ptr = &temp; // Pointer to it
return ptr; // Returning the pointer
}

int main() {
int *dangling = getScopedPointer();

// dangling is now a dangling pointer in C
printf("Value from dangling pointer: %d\n", *dangling); // Undefined behavior

return 0;
}

Output

Value from dangling pointer: [garbage or segmentation fault]

Explanation

The variable `temp` exists only during the execution of `getScopedPointer()`. Once it exits, `temp` is gone. However, we’ve returned its address and stored it in `dangling`, making it a dangling pointer in C. This is a subtle error and hard to trace because the code might work “sometimes” during testing—making it even more dangerous in production.

Bonus Case: Using Memory After Reallocation

Reallocating memory can also cause a dangling pointer in C if you lose the original pointer before assigning the result of `realloc()` to a new one safely.

Example: Unsafe Reallocation

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

int main() {
int *ptr = (int *)malloc(2 * sizeof(int));
ptr[0] = 10;
ptr[1] = 20;

// realloc might move memory. If it fails, original memory is leaked
ptr = realloc(ptr, 4 * sizeof(int)); // Safe in this case, but if not saved correctly, original ptr becomes dangling

printf("Value after realloc: %d\n", ptr[0]);

free(ptr); // Clean up

return 0;
}

Expected Output (if realloc succeeds):

Value after realloc: 10

Output (if realloc fails)

NULL

Explanation

In this example, if you had written something like:

realloc(ptr, 4 * sizeof(int)); // Not assigning it back

Then the original `ptr` would become a dangling pointer in C if `realloc()` moves the memory. Always capture the result of `realloc()` in a temporary pointer first to avoid this.

How To Avoid Dangling Pointer in C?

Now that we’ve seen how dangerous a dangling pointer in C can be—and how it’s commonly created—let’s talk about prevention. The good news? Avoiding a dangling pointer in C is very possible with some disciplined practices and habits.

Let’s walk through key techniques to keep your pointers safe, stable, and sane.

1. Set Pointers to NULL After Freeing

One of the simplest and most effective ways to avoid a dangling pointer in C is to explicitly set the pointer to `NULL` right after calling `free()`.

Example: Nullifying After Freeing

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

int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 30;

free(ptr); // Memory freed
ptr = NULL; // Pointer nullified to avoid dangling pointer in C

// Safe: won't crash, just doesn't do anything
if (ptr != NULL) {
printf("Value: %d\n", *ptr);
} else {
printf("Pointer is NULL, safe from dangling pointer in C.\n");
}

return 0;
}

Output

Pointer is NULL, safe from dangling pointer in C.

Explanation

After freeing, setting the pointer to `NULL` ensures you don't accidentally use it. In C, dereferencing a `NULL` pointer will crash immediately (e.g., segmentation fault), making the bug obvious—unlike silently using a dangling pointer in C, which may go unnoticed.

Also read about if-else statement in C and nested if-else statement to efficiently develop the code logic.

2. Use Temporary Pointers With realloc()

Improper use of `realloc()` is another sneaky way a dangling pointer in C can arise. If `realloc()` fails, it returns `NULL` and the original memory block remains valid. But if you overwrite your original pointer with `NULL`, you've now lost access to that memory—creating a leak and potentially leaving you with a dangling pointer in C.

Example: Safe realloc()

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

int main() {
int *ptr = (int *)malloc(2 * sizeof(int));
ptr[0] = 1;
ptr[1] = 2;

// Use a temporary pointer
int *temp = realloc(ptr, 4 * sizeof(int));
if (temp != NULL) {
ptr = temp; // Safe to assign
ptr[2] = 3;
ptr[3] = 4;

printf("Values: %d, %d, %d, %d\n", ptr[0], ptr[1], ptr[2], ptr[3]);
} else {
// realloc failed; original ptr is still valid
printf("Memory reallocation failed. Avoided dangling pointer in C.\n");
free(ptr); // Always clean up
}

return 0;
}

Output (on success)

Values: 1, 2, 3, 4

3. Never Return Address of Local Variables

This one’s a classic mistake. Returning the address of a local (stack) variable creates a dangling pointer in C because the variable goes out of scope when the function ends.

What to Do Instead?

  • Use dynamically allocated memory (with `malloc()`)
  • Or, pass the result by reference using function parameters

Fixed Version Example

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

int* getSafePointer() {
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated
*ptr = 55;
return ptr; // This is safe
}

int main() {
int *safePtr = getSafePointer();
printf("Safe value: %d\n", *safePtr);

free(safePtr); // Always free your allocations

return 0;
}

Output

Safe value: 55

4. Scope Awareness: Don't Use Out-of-Scope Addresses

Another reliable way to create a dangling pointer in C is to reference a variable after it has gone out of scope.

Fix: Define Variables in the Right Scope

Ensure that any variable a pointer references will outlive the pointer itself.

#include <stdio.h>

void assignPointer(int p) {
static int safeVar = 77; // static retains scope beyond function
*p = &safeVar;
}

int main() {
int *ptr = NULL;
assignPointer(&ptr);

printf("Value from static variable: %d\n", *ptr); // Safe

return 0;
}

Output

Value from static variable: 77

Explanation

The use of `static` ensures `safeVar` persists even after `assignPointer()` exits, avoiding the dangling pointer in C issue.

Also explore article on compiling C program on Linux to master programming across operating systems.

5. Use Static or Global Variables (When Appropriate)

If you need to return a reference that lasts longer than a function's scope—but don’t want to dynamically allocate memory—`static` or global variables are an option. Just be cautious with concurrency and side effects.

Conclusion

The dangling pointer in C is one of those bugs that can be both elusive and catastrophic. It creeps in silently, often during seemingly harmless memory operations—accessing freed memory, returning local addresses, or misusing scoped variables. And once it shows up, it can crash your program, corrupt your data, or worse—cause undefined behavior that’s hard to trace.

You've seen how a dangling pointer in C is created and why it's so dangerous. More importantly, you've learned practical, real-world techniques to prevent it. From nullifying pointers after freeing them, to using safer realloc() patterns, to understanding variable scopes—these strategies will help you write safer, cleaner C code.

In a language as powerful and low-level as C, pointer safety is your responsibility. With great power comes great responsibility—and now, with great understanding, you’re better equipped to tame the dangers of the dangling pointer in C.

FAQs

1. Is a dangling pointer in C the same as a wild pointer?

No, a dangling pointer in C is a pointer that was once valid but now points to deallocated or out-of-scope memory. A wild pointer, on the other hand, is a pointer that has not been initialized at all. Both are dangerous, but a dangling pointer was previously valid, while a wild pointer never was.

2. How do dangling pointers differ from null pointers?

A dangling pointer in C points to a previously valid memory location that is no longer accessible. A null pointer, on the other hand, is explicitly set to NULL and does not point to any memory. Accessing a null pointer results in a crash, but it’s safer than silently using a dangling pointer.

3. What causes dangling pointers in C?

Dangling pointers are typically caused by freeing dynamically allocated memory and then continuing to use the pointer, returning the address of local variables, or using pointers to variables that have gone out of scope. These situations leave the pointer pointing to memory that is no longer valid for access.

4. Can the compiler detect a dangling pointer in C?

No, most C compilers do not detect dangling pointers at compile time. Dangling pointers are a runtime issue, and because they still hold valid-looking addresses, they don’t raise immediate flags. Tools like Valgrind or AddressSanitizer can help detect them during execution by tracking memory usage and pointer behavior.

5. What are the risks of using a dangling pointer in C?

Using a dangling pointer in C can lead to segmentation faults, memory corruption, data loss, and undefined program behavior. The worst part is that some bugs caused by dangling pointers might not crash immediately, making them hard to detect and debug. These bugs can silently alter program logic and corrupt data.

6. How do I safely free memory without causing a dangling pointer?

Always set your pointer to NULL after calling free(). This prevents accidental use of freed memory. Before accessing any pointer, check if it is NULL. This small habit makes it easier to identify invalid access attempts and helps reduce the chance of introducing a dangling pointer in C into your code.

7. What happens if I access a dangling pointer?

Accessing a dangling pointer in C invokes undefined behavior. This can cause the program to crash, return garbage values, or even seem to work normally while causing subtle bugs. Since the memory pointed to might have been reallocated elsewhere, you're essentially tampering with something you no longer own or control.

8. Can a global variable become a dangling pointer?

Global variables themselves don’t go out of scope and typically don’t become dangling pointers. However, if a global pointer variable is set to point to dynamically allocated memory that is later freed, and you continue to use that pointer, it becomes a dangling pointer in C just like any other.

9. Are static variables safe from dangling pointer issues?

Yes, static variables are not destroyed when a function exits, so returning their address does not create a dangling pointer in C. They're stored in a different memory segment that persists for the program’s lifetime, making them a safe alternative when a function needs to return a persistent reference.

10. How does Valgrind help with dangling pointers?

Valgrind is a powerful memory debugging tool that helps detect memory leaks, use-after-free errors, and dangling pointers in C. It tracks allocated memory and alerts you when your code accesses memory that has already been freed or is no longer valid, helping you catch bugs during testing and development.

11. Can pointers in C++ also become dangling?

Yes, dangling pointer issues are not limited to C. In C++, you can also have dangling pointers when deleting dynamically allocated memory with delete or delete\[], and continuing to use the pointer. Modern C++ encourages using smart pointers, which automatically manage memory and significantly reduce the chance of dangling pointer errors.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.