Pointer p in the first example dangles, as already explained.
Function
DeleteList()
is fine internally, but it still could be problematic, because the caller still holds a non-null pointer to the head of the deleted list, which now points into invalidated memory:
void foo() {
List_T* my_list = new List_T;
my_list->data = 42;
my_list->pNext = nullptr;
if (my_list)
std::cout << my_list->data; DeleteList(my_list);
if (my_list)
std::cout << my_list->data; }
If you want to clean that pointer too, you have to pass it by reference and set it to 0:
void DeleteList(List_T*& pHead)
{
while(pHead)
{
List_T* tmp = pHead->pNext;
delete pHead;
pHead = tmp;
}
pHead = nullptr;
}
With this change the function foo() above will not try to access the invalidated pointer.