Array Dynamic resize in heap
If you had tagged this code as C, it would have been acceptable. Since you tagged it as C++, it's horrible.

Instead of writing your own swap function, there's already std::swap in &lt;algorithm&gt;.

Instead of writing bubble sort yourself, just use std::sort, also from &lt;algorithm&gt;.

Instead of using arrays and resizing them yourself, just use std::vector&lt;int&gt;, from &lt;vector&gt;.

After applying these transformations, you cannot have a dangling pointer anymore since your code is completely pointer-free.

As part of an exercise for learning the basic operations on memory management, it's ok to write code like this, but never ever use such code in production. In production the code should look like this:

#include &lt;algorithm&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

void Print(const std::vector&lt;int&gt; &amp;nums)
{
    for(int num : nums)
    {
        std::cout &lt;&lt; " " &lt;&lt; num;
    }
    std::cout &lt;&lt; "\n";
}

int main()
{
    std::vector&lt;int&gt; nums { 5, 7, 3, 1 };

    // There's probably a more elegant way to add the elements to the vector.
    nums.push_back(4);
    nums.push_back(2);
    nums.push_back(8);

    std::sort(nums.begin(), nums.end());

    Print(nums);
}


By the way, your original code doesn't have any dangling pointer as well. Well done.

You don't need the != NULL check before the delete[] since that pointer cannot be null. In modern C++ (since C++11 I think) you would also write nullptr instead of NULL. The reason is that historically NULL had not been guaranteed to be of pointer type.

Have a look at https://en.cppreference.com/w/cpp/algorithm for more algorithms that you shouldn't implement yourself in C++.

I would have liked to write the push_back block in a shorter way, as well as the Print function. I'm sure there's a more elegant way, I just don't know it.