Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

C++ Memory Leakage?

So I am relatively new to C++ and coding in general, and have an assignment that requires me to have minimal memory leakage. I get the general idea, but I do not understand where to put the different delete commands. If someone could help me on where to put delete commands for this insert function for a sorted single linked list, I could figure it out from there. Thanks
[CODE title="Insert"]bool LList::Insert(InfoType* x_ptr)
{
Node* n = new Node(x_ptr, list);
if (IsEmpty())//if true, starts a new list
{
list = n;
return true;
}
else//if list already started
{
if (*list->infoPtr == *x_ptr)//if true, first element is equal to new element
{
return false;
}
else if (*x_ptr < *list->infoPtr)//if true, first element comes after new element
{
list = n;
return true;
}
else //if here, first element comes before new element
{
Node* current = list;
while (current->next != NULL && *current->next->infoPtr < *x_ptr)//if true, current->next exists and comes before new element
current = current->next;
if (current->next != NULL && *current->next->infoPtr == *x_ptr)// if true, element already exists
{
return false;
}
else {//if here, add a new element in found location
Node* w = new Node(x_ptr, current->next);
current->next = w;
return true;
}
}
}
}[/CODE]
 
Hi ShadowedKitty,

If you write the following:
C++:
x_ptr->~Fruit();
You only destroy the class object. You do not free the memory that has been reserved for it.
If you do the following:
C++:
delete x_ptr;
Then the destructor of the object will be automatically called and the memory it used will be freed.

You should used 'delete' only when an object is taken off the list or when the list itself is destroyed.
 
Back
Top Bottom