Dangling Pointers
What Are Dangling Pointers?
- Definition: A dangling pointer is a pointer that points to memory that has been deallocated.
- Cause: Occurs when a function returns a pointer to a local variable. The local variable’s memory is deallocated when the function ends, leaving the pointer pointing to invalid memory.
Issues with Dangling Pointers
- Undefined Behavior: Dereferencing a dangling pointer can lead to unpredictable behavior, as the memory it points to no longer holds valid data.
- Compiler Warnings: Some compilers warn about returning local variable addresses, but their detection is limited and not foolproof.
Example of a Dangling Pointer
int *initArray(int howLarge) {
int myArray[howLarge];
for (int i = 0; i < howLarge; i++) {
myArray[i] = i;
}
int *p = myArray;
return p; // Returns pointer to deallocated memory
}
- Explanation: In the above code,
myArray
is deallocated when initArray
returns, making p
a dangling pointer.
Risks and Misconceptions
- Occasional Functionality: Sometimes, using a dangling pointer might not immediately show problems because the memory isn’t reused right away.
- Dangerous Habits: This false sense of security can lead to bad coding practices, especially for novices.
Memory Behavior
- Persistent Values: Memory values remain until overwritten.
- Stack Frame Reuse: Deallocated memory is reused when new values are placed on the stack, leading to potential overwriting and unpredictable changes.
Key Takeaway: ALWAYS avoid returning pointers to local variables from functions to prevent creating dangling pointers and undefined behavior in your code.
Array Size
Array Indices and Size