On Tue, 5 Apr 2016 00:43:03 -0700 (PDT), Paul <
peps...@gmail.com>
wrote:
>My code below seems to run fine but I'm not happy with the memory management side of it. The explore function is supposed to delete the pointers in vertices which is a vector of pointers and replace them with the new v.
>However, this doesn't seem to work. In function explore, I'm confused by the fact that vertices[index]->component seems to give the correct value, straight after I've done delete vertices[index]; I would have expected a runtime crash.
Evaluating a pointer after the memory it points to has been released
causes undefined behavior. While a crash at this point is certainly
desirable, you cannot depend on any particular result.
>Also, what is the simplest method here to avoid memory leaks? The values of vertices[index] are allocated using new. I'm assuming that changing them (such as vertices[index] = v;) will leak memory. Is this correct? Or is delete vertices[index]; unnecessary?
The only method of avoiding memory leaks is careful programming. If a
pointer points to allocated memory and you assign a new value to the
pointer, the allocated memory becomes inaccessible for any purpose and
you have a memory leak. On most modern systems, any allocated memory
will be recovered by the system when your program terminates. However,
issuing a delete for every new is still considered good practice.
>I'm interested in the case where vertex is replaced by a much more complex struct or class whose objects are not limited to ints.
The type of object pointed to is not a deciding factor. If the memory
was dynamically allocated, it should be released.
If the object contains pointers to other dynamically allocated memory,
then you need to release in the reverse order of the allocations. If
pointer a points to dynamic object b which contains a pointer c which
also points to dynamic memory, you would delete a->c before you delete
a.
--
Remove del for email