Crash in custom Linked List using delete

Started by
4 comments, last by _paf 11 years, 2 months ago

Okay, so i'm making a custom linked list class using templates, and i'm having a problem when removing elements from it, more specifically at the delete instruction.

Here's the code for the class


#ifndef _LINKED_LIST_H_
#define _LINKED_LIST_H_

#include <cstring>

template <typename Type>
struct sNode
{
    //Pointer to the next element
    sNode *next;

    //This element's data
    Type data;
};

template <typename Type>
class LinkedList
{

//Public Properties
public:

//Private Properties
private:
    //The root element
    sNode<Type> *first;

    //The last element
    sNode<Type> *last;

    //The number of elements
    unsigned short numNodes;

//Public Methods
public:
    //Default constructor
    LinkedList();

    //Destructor
    ~LinkedList();

    //Add an element (empty)
    bool Insert(Type **address);

    //Removes an element
    bool Remove(Type **address);

    //DEBUG: Dump the linked list
    void Dump();

//Private Methods
private:

};

//-------------------- Constructor / Destructor --------------------

template <typename Type>
LinkedList<Type>::LinkedList()
    :first(NULL),
     last(NULL),
     numNodes(0)
{

}

template <typename Type>
LinkedList<Type>::~LinkedList()
{
    //TODO: Clear the list here!
}

//-------------------- Public Methods --------------------

template <typename Type>
bool LinkedList<Type>::Insert(Type **pAddress)
{
      //Check if there are no elements
      if(!this->first)
      {

      //Allocate space for the new element
      this->first = new sNode<Type>;

      //The first element is also the last
      this->last = this->first;

      //Set the pointer to this struct (to return)
      (*pAddress) = &this->first->data;

      //OPT: Initialize data to 0
      memset(&this->first->data, 0, sizeof(sNode<Type>));

      //OPT: Set 'next' pointer to NULL
      this->first->next = NULL;
      this->last->next = NULL;

      }
      //There's already at least an element
      else
      {

      //Allocate space for the new element
      this->last->next = new sNode<Type>;

      //Point to the last
      this->last = this->last->next;

      //Set the pointer to this struct (to return)
      (*pAddress) = &this->last->data;

      //OPT: Initialize data to 0
      memset(&this->last->data, 0, sizeof(sNode<Type>));

      //OPT: Set 'next' pointer to NULL
      this->last->next = NULL;

      }

    //Update the number of elements
    this->numNodes++;

    return true;
}

//Removes an element
template <typename Type>
bool LinkedList<Type>::Remove(Type **pAddress)
{
      //Check for NULL address
      if(!(*pAddress))
      return false;

    //---------- Check if the 1st element matches ----------

      //Check if the 1st DATA address matches the given address
      if(&this->first->data == *pAddress)
      {

      //VAR: Pointer to the current node on the list
      sNode<Type> *ptr = this->first->next;

      //Delete the element
      delete this->first;
      this->first = NULL;

      //Set the next element as the next
      this->first = ptr;

      //Update the node counter
      this->numNodes--;

      //Set the address to NULL
      (*pAddress) = NULL;

      return true;

      }

    //---------- Check if any other element matches ----------

    //VAR: Pointer to the current node on the list
    sNode<Type> *ptr = this->first->next;

    //VAR: Pointer to the 2nd to current node on the list
    //     Will be used for pointing to the element after the one deleted
    sNode<Type> *last = this->first;

      //Loop through the list until the node is found (IF it is found)
      do
      {

        //Check if the addresses match
        if(&ptr->data == *pAddress)
        {

        //VAR: Pointer to the next element
        sNode<Type> *nex = ptr->next;

        //Delete the element
        delete ptr;
        ptr = NULL;

        //Set the element before, point to the next
        last->next = nex;

        //Update the node counter
        this->numNodes--;

        //Set the address to NULL
        (*pAddress) = NULL;

        return true;

        }

      //The address didn't match, so update the pointers
      last = ptr;
      ptr = ptr->next;

      }
      while(ptr->next);

    //---------- Check if the last element matches ----------

      //Check if the addresses match
      if(&ptr->data == *pAddress)
      {

      //Delete the element
      delete ptr;
      ptr = NULL;

      //Point to the last element
      this->last = last;

      //Set the element before, point to the next
      last->next = NULL;

      //Update the node counter
      this->numNodes--;

      //Set the address to NULL
      (*pAddress) = NULL;

      return true;

      }

    return false;
}

//DEBUG: Dump the linked list
template <typename Type>
void LinkedList<Type>::Dump()
{
    printf("Nodes: %i\n", this->numNodes);

    sNode<Type> *ptr = this->first;

      while(ptr)
      {
      printf("PTR: 0x%08X NEXT: 0x%08X DADR: 0x%08X DATA: %i\n", ptr, ptr->next, &ptr->data, ptr->data);
      ptr = ptr->next;
      }
}

//-------------------- Private Methods --------------------

//-------------------- Get / Set --------------------

#endif //_LINKED_LIST_H_

And, if it help, here's the main


#include <cstdio>
#include <conio.h>
#include "LinkedList.h"

int main()
{
    LinkedList<int> my;
    int *ptr1 = NULL;
    int *ptr2 = NULL;
    int *ptr3 = NULL;
    int *ptr4 = NULL;

    //printf("Nodes: %i\n", my.numNodes);

    my.Insert(&ptr1); *ptr1 = 333;
    printf("ADR: 0x%08X PNT: 0x%08X VAL: %i\n", &ptr1, ptr1, *ptr1);
    my.Insert(&ptr2); *ptr2 = 666;
    printf("ADR: 0x%08X PNT: 0x%08X VAL: %i\n", &ptr2, ptr2, *ptr2);
    my.Insert(&ptr3); *ptr3 = 999;
    printf("ADR: 0x%08X PNT: 0x%08X VAL: %i\n\n", &ptr3, ptr3, *ptr3);

    my.Remove(&ptr3);

    my.Insert(&ptr4); *ptr4 = 1222;
    printf("ADR: 0x%08X PNT: 0x%08X VAL: %i\n\n", &ptr4, ptr4, *ptr4);
    
    //my.Remove(&ptr3);
    my.Dump();

    _getch();
    return 0;
}

Now the problem is that when calling the Remove method, when the program reaches the delete instruction (any of them) it crashes with the error "Heap corruption detected".

I don't know if i'm just fed up with pointers, that i can't find the error, or if it is something else, so please help.

NOTE: I know that there are already Linked List classes, and that the way i made it may not (and probably isn't) be the best way to do it, but try to bear with it.

Thanks in advance.

Advertisement

      //OPT: Initialize data to 0
      memset(&this->last->data, 0, sizeof(sNode<Type>));

You memset() more than the actual size, in other words, this->last->data is smaller than sizeof(sNode<Type>), that might be the issue.

You really shouldn't be memseting the data to zero. It'll wreck havock for more complex data types (for example, if it's a custom data type that initializes its members in some specific way, and you reset them to zero!). Not to mention, you're overflowing on your memseting:


memset(&this->first->data, 0, sizeof(sNode<Type>)); // data is a Type, not a sNode<Type>!

should be:


memset(&this->first->data, 0, sizeof(Type)); // But still, you shouldn't be doing this anyway


This can lead to all sorts of problems later on, like crashing.

You also want to change your do...while() loop in your deleter to be a while() loop (what if first->next is null?). Also, you're breaking your linked list. If you're deleting some node N, you need to set the previous node's next to be N->next. I won't completely rewrite it for you, as I want you to try.

Also, someday you'll want to implement the Rule of Three.

[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

First of all thank you both, the problem was indeed memset() (spend so much time looking at Type and sNode<Type> stuff, that i completely blew it).

Also, Cornstalks, you're right again, i overlooked that if first->next might be NULL.

But when i delete a node other than the last, i do set the previous node's next to point to the deleted node's next (if you want, try the code above). This is not done ONLY for the last element, because there's no next element after it.

Oh, and i declared the destructor, but i didn't clear the list there because i was still testing removing elements, so i haven't implemented it yet.

And you mention the rule of three, C++ will create those constructors if you don't, right? How would the default copy constructor work in this case?

Also, if i don't want to allow for both copy constructors, can i declare the assignment constructor private?

I really haven't thought of that yet, because i was stuck in the Remove method, and haven't done anything else yet.

And you're right yet again in not rewriting it for me. Practice makes perfect, and what better way to learn it than doing it?

Again thank you both.

First of all thank you both, the problem was indeed memset() (spend so much time looking at Type and sNode<Type> stuff, that i completely blew it).

Also, Cornstalks, you're right again, i overlooked that if first->next might be NULL.
But when i delete a node other than the last, i do set the previous node's next to point to the deleted node's next (if you want, try the code above). This is not done ONLY for the last element, because there's no next element after it.

Ah, I see, I got confused. You might want to rename last to something like previous (it's horribly confusing with this->last) :)

Oh, and i declared the destructor, but i didn't clear the list there because i was still testing removing elements, so i haven't implemented it yet.
And you mention the rule of three, C++ will create those constructors if you don't, right? How would the default copy constructor work in this case?

It'll create a copy and assignment constructor for you, but they won't do what you want. They'll just copy the pointers, which means you've got two lists using the same set of pointers, and they'll both try to delete the same pointers when they clean up. Or they'll be modifying the same pointers. The difference is a "shallow copy" vs a "deep copy." The default copy constructor and assignment operator will perform a shallow copy.

Also, if i don't want to allow for both copy constructors, can i declare the assignment constructor private?

Yeah, you can make them private. That works.

[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

Ok, thanks.

This topic is closed to new replies.

Advertisement