Eroxl's Notes
Dangling Pointers

When a program accesses memory that has already been freed, the contents at that location are undefined because the system may have reallocated that memory for other purposes. Pointers pointing to this freed memory are called dangling pointers.

Example

int *i = new int;
*i = 5;
delete i;

cout << *i << endl;

Here, i points to memory that has been deallocated. Accessing or writing to it can produce unexpected results.

Avoiding Dangling Pointers

To prevent using freed memory, you can set the pointer to NULL after deletion. This way, dereferencing it will trigger a crash (e.g., segmentation fault), making the bug easier to detect:

int *i = new int;
*i = 5;
delete i;
i = NULL;

cout << *i << endl; // Seg fault