c++ - Deallocate pointer to a struct preserving memory addresses of nested variables -


template<typename t> t& list<t>::popfront() {     if (head == null)         throw std::underflow_error("list error: no head node available\n");     if (tail == head)         tail = null;     t item = head->item;     head = head->next;     return item; } 

i have recursive struct listnode following fields:

template <typename t> struct listnode {     t item;     listnode* next;     ... } 

the problem want deallocate head node after popfront procedure, nested nodes indirectly pointing same address, addresses vanish heap. can see above alter pointer address of head node next one, believe leads memory leak.

i not exclude i'm absolutely wrong approach , assumption. please, consider efficient way perform such task, if deallocation necessary.

there couple of problems here.

template<typename t> t& list<t>::popfront() {     if (head == null)         throw std::underflow_error("list error: no head node available\n");     if (tail == head)         tail = null;     t item = head->item;     head = head->next; //memory leak, lost pointer head item     return item; //returning reference stack variable, undefined behavior } 

i suggest change signature return value, can return local , deallocate element in heap.

template<typename t> t list<t>::popfront() {     if (head == null)         throw std::underflow_error("list error: no head node available\n");     if (tail == head)         tail = null;     t item = head->item;     listnode* old_head = head; //keep deallocation     head = head->next;     delete old_head; //deallocate old head     return item; //return value } 

you could, of course, adopt behavior of std::list , have different methods access , popping, front() , pop_front() respectively.

as per signature, front() returns reference, far more efficient if t heavy object.

this assuming you're doing academic purposes, of course. otherwise, well, use std::list or similar standard library container.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -