Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Do these sections of C++ code have a memory leak? I've used the valgrind test and it says there are memory leaks, but I'm not

Do these sections of C++ code have a memory leak? I've used the valgrind test and it says there are memory leaks, but I'm not sure where it's located. The functions below are a copy constructor(with helper function), a destructor(with helper function), enqueue, dequeue, and overloaded assignment operator function. Do these functions have memory leaks? If so, where? QueueT is a class template and NodeT is a class that points to the next data node. Thanks

// helper function for deep copying queue template void QueueT::copy_queue(const QueueT& q) { front = nullptr; back = nullptr; current_size = q.current_size; NodeT* original = q.front; if (original != nullptr) { front = new NodeT(original->data); original = original->next; NodeT* copy = front; while (original != nullptr) { NodeT* newNode = new NodeT(original->data); copy->next = newNode; copy = copy->next; original = original->next; } } }

// copy constructor template QueueT::QueueT(const QueueT& q) { copy_queue(q); }

// helper function for deleting queue template void QueueT::delete_queue() { NodeT* temp = front; if (front != nullptr) { front = front->next; delete temp; temp = front; } current_size = 0; }

// destructor template QueueT::~QueueT() { delete_queue(); }

// overloaded assignment operator template QueueT& QueueT::operator=(const QueueT& q) { if (this != &q) { delete_queue(); copy_queue(q); } return *this; }

// enqueue template void QueueT::enqueue(T val) { NodeT* temp = new NodeT(val); if (front == nullptr) { front = back = temp; } else // if not, then it points to the next { back = back->next = temp; } current_size++; }

// dequeue template T QueueT::dequeue() { if (empty()) { throw runtime_error("the queue is empty"); } NodeT* temp = front; T result = front->data; front = front->next; delete (temp); current_size--; return result; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions