• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
__SKYe

Crash in custom Linked List using delete

5 posts in this topic

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.

0

Share this post


Link to post
Share on other sites
      //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.

2

Share this post


Link to post
Share on other sites

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.

Edited by Cornstalks
2

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0