• 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
ISDCaptain01

My heap sort keeps on crashing (C++)

12 posts in this topic

I made a heapsort today, but when I run it, I always get an error and my compiler aborts the program

Well here is my walkdown algorithm:

 

template <class DataType>

//HeapWalkDown: Walks down an a node in array

//               (Array, Index of parent of the lowest node, Size of the array, comparison function)
void HeapWalkDown( Array<DataType> &p_array, int p_index, int p_maxIndex, int (*p_compare)(DataType, DataType))
{
	//Keeps track of the current parent index
	int parent = p_index;

	//Keeps track of the current child index
	int child  = p_index * 2;

	//Stores the data that is being walked down into a temporary variable
	DataType temp = p_array[parent];

	//Starts a loop, loops through the tree until the child index is
	//greater then the tree size
	while(child <= p_maxIndex)
	{
		//If the left child is not the last node in the tree, then
		//find out which of the current node's children is the largest
		if(child < p_maxIndex)
		{
			//Compare the left and right child to see which one holds
			//the larger value

		    //           LEFT CHILD        RIGHT CHILD
			if(p_compare(p_array[child], p_array[child + 1]) < 0)
			{
				//If the right child has the larger, then increment the child index
				//because the the index of the right child is always is one larger
				//then the left child
				child++;
			}
		}

		//Now the function knows which child it wants to move upward. It
        //Determines if the child node needs to move upward by comparing
	    //it to the value in the temp variable
        if(p_compare(temp, p_array[child]) < 0)
		{
			//Moves the child upward into the parent index
			p_array[parent] = p_array[child];

			//
			parent = child;
			child *= 2;
		}

		//If no swap is needed
		else
		{
			break;
		}
	}

	//The value in temp is placed into the correct index
	p_array[parent] = temp;
}

and heres the heapsort function:

//Heapsort: Sorts an array into a heap, then turn the heap into a 
//sorted array
template <class DataType>
void Heapsort( Array<DataType> &p_array, int (*p_compare)(DataType, DataType))
{
	//Used to loop through the array
	int index;

	//Keeps track of the size of the array
	int maxIndex = p_array.Size();

	//The index of the last node's parent
	int rightindex = maxIndex/2;

	//Turns the array into a heap by walking down everything to
	//its proper place
	for(index = rightindex; index > 0; index--)
	{
		//Walk everything down, turning the array into a heap
		HeapWalkDown(p_array, index, maxIndex, p_compare);
	}

	//Starts creating a sorted array from the newly formed heap
	while(maxIndex > 0)
	{
		//Swap the root with the last node in the tree
		Swap(p_array[0], p_array[maxIndex - 1]);

		//Decrease the size of the tree
		maxIndex--;

		//Walk Down the top index
		HeapWalkDown(p_array, 1, maxIndex, p_compare);
	}
}




//Swap: Swap a left and right variable around
template <class DataType>
void Swap( DataType& a, DataType& b )
{
    static DataType t;
    t = a;
    a = b;
    b = t;
}



Note they all are in one header file

 

and here is my source file which demonstrates the sort

#include <iostream>
#include "Array.h"
#include "Heapsort2.h"
#include <stdlib.h>
#include <time.h>
using namespace std;


//Comparison function
int intcompare(int l, int r)
{
	return l - r;
}

int comparereverseint(int l, int r)
{
	return r - l;
}

int comparefloat(float l, float r)
{
	if(l > r)
		return 1;
	if(l < r)
		return -1;
	return 0;
}

//Function automatically prints an array
template <class DataType>
void PrintArray(Array<DataType> p_array)
{
	for(int i = 0; i < p_array.m_size; i++)
	{
		cout << p_array[i] << ", ";
	}
	cout << endl << endl;
}


int main()
{

	//Create two arrays
	Array<int> iarray(16);
	Array<float> farray(16);

	//Seed the random number generator
	srand(time(0));

	//Fills the array with random values
	for(int index = 0; index < 16; index++)
	{
		iarray[index] = rand() % 256;
		farray[index] = (float)(rand() % 256) / 256.0f;
	}

	//Display the Unsorted arrays
	cout << "Unsorted Integer array: " << endl;
	PrintArray(iarray);

    cout << "Unsorted Float array: " << endl;
	PrintArray(farray);

	
	//Sort the arrays
	HeapSort(iarray, intcompare);
	HeapSort(farray, comparefloat);

	
	//Display the sorted arrays
	cout << "Sorted Integer array: " << endl;
	PrintArray(iarray);

	cout << "Sorted Float array: " << endl;
	PrintArray(farray);


	cin.get();
	return 0;
}

any help would be appreciated

0

Share this post


Link to post
Share on other sites
I haven't looked into your crash problem yet, first a few other observations:

In your Swap method, you made t static. This doesn't really gain you anything, and it takes away the ability to use this in a multi-threaded scenario. I suggest removing the static keyword.

Be careful with the cheap comparison hack of return l - r; It doesn't work in every case, e.g. when r is MIN_INT. The way comparefloat does it is safer.

More commenting isn't always good. Too little is a common problem, but too much can also be a problem. It does depend on the nature of the commenting though. The most important thing to comment is always "Why". Avoid stating the obvious, e.g. "Create two arrays".

This "Array" class seems to be some kind of custom array type with an overloaded [] operator. This is good news as it means that you can add bounds checking to that operator, and hopefully it will find the bug for you. It's almost certainly an out-of-bounds access issue.
Perhaps use asserts for this so that your release build performance isn't affected. Edited by iMalc
0

Share this post


Link to post
Share on other sites

I looked at that article and im still lost. The compiler only throws that window at me and give me no idea of where it went wrong

Edited by ISDCaptain01
0

Share this post


Link to post
Share on other sites

Here it is:

 

#pragma once
#include <iostream>
using namespace std;

template <class Datatype>
class Array
{
public:

	//pointer to the array
	Datatype *m_array;

	//the arrays size
	int m_size;

	//the constructor
	Array(int p_size)
	{
		//pointer is used to allocate the specified amount that was passed in
		m_array = new Datatype[p_size];
		//member size variable is now equivalent to the passed in size variable
		m_size = p_size;
	}

	//the destructor
	~Array()
	{
		//deallocates the array and then makes the pointer point to NULL/0
		if(m_array != 0)
		{
			delete[] m_array;
		}
		m_array = 0;
	}

	//the array resize function
	void Resize(int p_size)  //first you gotta pass in the value of the new size you want
	{
		//pointer to the newly allocated array
		Datatype *newarray = new Datatype[p_size];
		if(newarray == 0) //if the newarray points to nothing
		{
			return;  //then exit the function
		}

		int min;
		if(p_size < m_size)
		{
			//if the passed in size is less then the size of the original array
			//than min variable equals the passed in size;
			min = p_size;
		}
		else
		{
			//if the passed in size is greater than or equal to the old array size
			//than min equal m_size
			min = m_size;
		}

		int index; //the iterator for the for loop
		for(index = 0; index < min; index++)
		{
			newarray[index] = m_array[index]; // copying from old array to new array
		}

		m_size = p_size;  //the member size is now updated to reflect the size of the new array

		if(m_array != 0)
		{
			delete[] m_array;
		}
		m_array = newarray;
	}

	Datatype& operator[](int p_index) //this opertor overload allows you to change the the value
	{                                 //of the array at any index by using normal syntax like intarray[5] = 42
		return m_array[p_index];      // rather than intarray.m_array[5] = 42 
	}

	operator Datatype*()    //lets you pass in an array declared in many different types of forms into the function
	{                       //conversion operator overload
		return m_array;
	}

	void Insert(Datatype p_item, int p_index) //pass in the value you want to insert at the location you want
	{
		int index;  //sets up an iterator
		for(index = m_size - 1; index > p_index; index--) //index equals the size of the array minus one
		{                                                 //as long as the index is greater than p_index(insertion area)
			m_array[index] = m_array[index - 1];          //keep on copying the previous index to the current index
			m_array[p_index] = p_item;                    //once we reach the p_index(insertion area), we insert the 
		}                                                 // the value we passed in as p_item
	}

	void Remove(int p_index)                               //pass in the index you want to remove
	{
		int index;                                         //declares an interator
		for(index = p_index + 1;  index < m_size; index++) //the iterator index is located just one index above the area you want to remove
		{                                                  //as long as iterator index is less than the size of the array
			m_array[index-1] = m_array[index];             //keep on copying to the index right behing the intertor index
		}
	}

	int Size()  //function the retrives the array size
	{
		return m_size;
	}


//function that writes to the disk first
    bool WriteFile(const char p_filename[]) //pass in a file name
    {
	    FILE* outfile = 0; //pointer to a file opbject, currently set to NULL/0
	    int written = 0;    //keeps track of how many items were written
	    outfile = fopen(p_filename, "wb"); //the outfile pointer now points to the file you passed in, and opens it
	    if(outfile == 0) //checking to see if the file opened or not
	    {
		    return false; //if it isnt open, return false
	    }
	    written = fwrite (m_array, sizeof(datatype), m_size, outfile); //writing the data to the file,  pass in
	                                                             //(pointer to array, size of data, size of array, the destination file);
	
	    fclose(outfile); //close the file                            
	    if(written != m_size)//checking to see if the file was written or not
		{
		return false;  //if not, return flase
		}
	    return true; //if it did, return true;
	}

//function that reads the file from the disk
	bool ReadFile(const char p_filename[])
	{
		FILE* infile = 0;
		int read = 0;
		infile = fopen(p_filename, "rb");
		if(infile == 0)
		{
			return false;
		}
		read = fread(m_array, sieof(datatype), m_size, infile);
		fclose(infile);
		if(read != m_size)
		{
			return false;
		}
		return true;
	}


	
};
0

Share this post


Link to post
Share on other sites

If nothing else, I'd make a guess that your PrintArray() function will crash when trying to dereference deleted memory because you did not follow the Rule of Three in your Array class.

1

Share this post


Link to post
Share on other sites

You're passing your Array object to the PrintArray function by value rather than by reference. As a result the parameter is a copy of the passed in argument (and therefore its m_array member points to the same address), so when the destructor is invoked at the end of the function the memory pointed to by both instances is deleted.

Edited by MrP
1

Share this post


Link to post
Share on other sites

Wow, it finally worked. You guys were right, it was the PrintArray function not taking a reference to an array.

Once again, you guys are truly awesome. Thank you

0

Share this post


Link to post
Share on other sites
Since your Array class does not implement proper copy semantics you should explicitly delete the copy constructor and assignment operator (in C++11) or set them private (before C++11) to prevent an accidental copy (which never works with that class).

Considering how far your Array class is behind std::vector (both regarding features and correctness in other aspects) I would also strongly suggest that you either make implementing a proper array class the whole point of the learning experience (not as simple as it sounds) or using std::vector.

On a more personal note, if I ever catch you "using namespace std;" at the top of a header I'm forced to use or work with, I will hunt you down. Edited by BitMaster
2

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