A dangling pointer is a pointer that points to memory that has been deallocated or is no longer valid. This can happen in several situations:
Example of a dangling pointer:
int* get_value() {
int x = 5;
// Returns a pointer to a local variable
return &x;
}
int main() {
int* ptr = get_value();
// Undefined behavior
std::cout << *ptr << '\n';
}
To avoid dangling pointers:
unique_ptr
, shared_ptr
) to manage dynamic memory safely.Example of avoiding a dangling pointer with a smart pointer:
#include <memory>
#include <iostream>
std::unique_ptr<int> get_value() {
auto ptr = std::make_unique<int>(5);
return ptr; // Safely returns the unique_ptr
}
int main() {
auto ptr = get_value();
std::cout << "Value: " << *ptr; // Safe to use
}
Value: 5
By understanding the concept of dangling pointers and following best practices, you can write more robust and error-free C++Â code.
Answers to questions are automatically generated and may not have been reviewed.
Learn about stack allocation, limitations, and transitioning to the Free Store