Jump to content

  • Log In with Google      Sign In   
  • Create Account

NUCLEAR RABBIT

Member Since 12 Apr 2006
Offline Last Active Apr 19 2016 01:35 PM

Topics I've Started

Memory Allocation

17 April 2016 - 02:40 PM

Hello,

 

So I am editing a project I had where I was creating a queue. In my pop() method I am having an issue and I am not sure why. I am trying to free the memory of the Node I am popping from the queue and also returning the data from that Node to the user before it is deleted. When I comment out the free() method in the pop() method it works and when I uncomment the free() call I get heap memory crashes. Can anyone please help me see what I am doing wrong?

 

Queue.inl

template <typename T>
T Queue<T>::pop()
{
	if (isEmpty())
	{
		std::cout << "pop() was used, but the Queue is empty.\n\n";

		return NULL;
	}
	else
	{
		Node * temp = headNode;

		T removedItem = temp->data;

		headNode = headNode->nextNode;

		std::cout << "pop() was used and " << temp->data << " was removed from the Queue.\n\n";

		free(temp);

		size--;

		return removedItem;
	}
}

Queue.h

#pragma once

template <class T>
class Queue
{
	public:
		Queue();
		Queue(T newItem);
		void push(T newItem);
		void pop_all();
		T pop();
		T peek();
		bool isEmpty();
		int getSize();
	private:
		struct Node
		{
			T data;
			Node * nextNode;
		};

		Node LinkedList;
		Node * headNode; // front of the queue
		Node * tailNode; // End of the Queue
		int size;
};

#include "Queue.inl"

Data Structures Help!

06 April 2016 - 05:24 PM

UPDATE:

 

I finished the project last week that I needed help on (thanks for the help!) and I was wondering if someone wouldn't mind taking the time to look over my code and give me any tips/suggestions in my code. All is working with no bugs, but I am sure I didn't do something a more efficient way and I want to improve my code! Thanks in advance to any tips!

 

Main.cpp

//////////////////////////////////
//                              //
//   Data Structures - Queues   //
//   ------------------------   //
//                              //
//   Creating a queue system    //
//   using linked lists and     //
//   C++ (FIFO)                 //
//                              //
//////////////////////////////////

#include "LibIncludes.h"

int main()
{
	Queue<int> myQueue;

	myQueue.displayQueue();

	myQueue.pop();
	myQueue.peek();
	myQueue.pop_all();

	myQueue.push(2);
	myQueue.push(9);
	myQueue.push(3);

	myQueue.peek();

	myQueue.push(1);
	myQueue.push(7);
	myQueue.push(5);

	myQueue.displayQueue();

	myQueue.pop();
	myQueue.pop();

	myQueue.displayQueue();

	myQueue.pop_all();

	myQueue.displayQueue();

	system("PAUSE");

	return 0;
}

Queue.h

#pragma once

template <class T>
class Queue
{
	public:
		Queue();
		Queue(T newItem);
		void push(T newItem);
		void pop();
		void pop_all();
		void peek();
		bool isEmpty();
		void displayQueue();
	private:
		struct Node
		{
			T data;
			Node * nextNode;
		};

		Node LinkedList;
		Node * headNode; // front of the queue
		Node * tailNode; // End of the Queue
		int size;
};

#include "Queue.inl"

Queue.inl

#include "LibIncludes.h"

template <typename T>
Queue<T>::Queue()
{
	headNode = nullptr;
	tailNode = nullptr;

	size = 0;

	std::cout << "*** A new empty Queue was created ***\n\n";
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
Queue<T>::Queue(T newItem)
{
	Node * temp = (struct Node *)malloc(sizeof(struct Node *));

	temp->data = newItem;
	temp->nextNode = nullptr;

	headNode = temp;
	tailNode = temp;

	size = 1;

	std::cout << "*** A new Queue with starting item " << headNode->data << " was created ***\n\n";
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
bool Queue<T>::isEmpty()
{
	if (headNode == NULL)
		return true;
	else
		return false;
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
void Queue<T>::peek()
{
	if (isEmpty())
		std::cout << "peek() was used, but there is nothing in the Queue.\n\n";
	else
		std::cout << "peek() was used and resulted in: " << headNode->data << "\n\n";
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
void Queue<T>::pop_all()
{
	if (isEmpty())
		std::cout << "pop_all() was used, but the Queue is already empty.\n\n";
	else
	{
		std::cout << "pop_all() was used and destroyed the Queue.\n\n";

		headNode = nullptr;
		tailNode = nullptr;

		size = 0;
	}
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
void Queue<T>::push(T newItem)
{
	Node * temp = (struct Node *)malloc(sizeof(struct Node *));

	temp->data = newItem;
	temp->nextNode = nullptr;

	if (isEmpty())
	{
		headNode = temp;
		tailNode = temp;
	}
	else
	{
		tailNode->nextNode = temp;
		tailNode = temp;
	}

	size++;
	std::cout << "push() was called and " << newItem << " was added to the Queue.\n\n";
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
void Queue<T>::pop()
{
	if (isEmpty())
		std::cout << "pop() was used, but the Queue is empty.\n\n";
	else
	{
		Node * temp = headNode->nextNode;

		std::cout << "pop() was used and " << headNode->data << " was removed from the Queue.\n\n";

		headNode->nextNode = nullptr;
		headNode = temp;

		size--;
	}
}

///////////////////////////////////////////////////////////////////////////////

template <typename T>
void Queue<T>::displayQueue()
{
	std::cout << "\ndisplayQueue() was called:\n";
	std::cout << "------------------------- queue contents\n\n";

	std::cout << "*** QUEUE SIZE: " << size << std::endl;

	if (isEmpty())
	{
		std::cout << "*** Queue is empty\n";
	}
	else
	{
		Node * temp = headNode;

		while (temp != NULL)
		{
			std::cout << "- " << temp->data << "\n";

			temp = temp->nextNode;
		}
	}

	std::cout << "\n------------------------- end of queue\n\n";
}

LibIncludes.h

#pragma once

#include <iostream>
#include <string>

#include "Queue.h"

Original Post:

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Hello,

 

So I am trying to work on data structures and I am trying to implement the stack using linked lists. I only have a little bit done so far because I ran into an error and have no idea why it is happening. I've commented out the line in main that creates the LinkedStack object and it builds with no errors, but when I uncomment it I get 2 errors.

 

First error:

Severity    Code    Description    Project    File    Line    Suppression State
Error    LNK2019    unresolved external symbol "public: __thiscall LinkedStack<int>::LinkedStack<int>(void)" (??0?$LinkedStack@H@@QAE@XZ) referenced in function _main    DataStructures_Stacks2    C:\Users\Brandon\documents\visual studio 2015\Projects\DataStructures_Stacks2\DataStructures_Stacks2\Main.obj    1    
 

Second error:

Severity    Code    Description    Project    File    Line    Suppression State
Error    LNK1120    1 unresolved externals    DataStructures_Stacks2    C:\Users\Brandon\documents\visual studio 2015\Projects\DataStructures_Stacks2\Debug\DataStructures_Stacks2.exe    1    
 

If anyone can please help me fix this issue I would be greatly appreciative!

 

Main.cpp

/*************************************
*				     *
*   Data Structures - Linked Stack   *
*   ------------------------------   *
*				     *
*   Implementing the stack using     *
*   linked lists and C++             *
*                                    *
*   4/6/2016		             *
*				     *
*************************************/

#include "LibIncludes.h"

int main()
{
	LinkedStack<int> myStack;

	std::cout << "----------------------------\n";
	system("PAUSE");

	return 0;
}

LinkedStack.h

#pragma once

template <class T>
class LinkedStack
{
	public:
		LinkedStack();
		LinkedStack(T newItem);
		void push(T newItem);
		void pop();
		void peek();
		bool isEmpty();
	private:
		struct node
		{
			T data;
			node * nextNode;
		};

		node linkedList;
		node * headNode;
};

LinkedList.cpp

#include "LibIncludes.h"

template <class T>
LinkedStack<T>::LinkedStack()
{
	std::cout << "An empty Linked Stack was created.\n";

	linkedList.data = null;
	linkedList.nextNode = nullptr;
	headNode = linkedList;
}

C++ Deleting data from files

04 January 2016 - 10:06 PM

Hello,

 

I finished writing a Phonebook application today, I just wanted to practice dealing with writing/reading/handling data from external files. All went well and the application works just like I want it too, but I was just wondering if my implementation is "the correct" way of for deleting specific portions of txt files. I wrote the function 2 different ways, one by creating a vector filled with Person objects that contains info from the contact list and I use those to fill the contact list file and the other way (which is commented out) was done by writing to a tmp txt file with the data minus what I want to delete and write over the original file with whats in the tmp file. I didn't like this way because I had the tmp contact file list lingering around.

 

Any advice on the proper way of handling this type of task or if you know a better way please let me know! Thanks!

void Phonebook::deleteEntry()
{
	int selection;
	bool valid = false;

	do
	{
		displayAllEntries();

		if (num_of_contacts < 1)
			break;

		std::cout << "\n\n\t\t\t\t\tEnter in the Entry to delete (0 = Cancel): ";
		std::cin >> selection;

		valid = std::cin.good();

		// making sure the selection was an int value
		if (!valid)
		{
			std::cin.clear();
			std::cin.ignore(INT_MAX, '\n');
		}
		else
		{
			// checks if user has contacts to delete and if the selection
			// is in range
			if ((selection <= num_of_contacts) && (num_of_contacts > 0) && (selection != 0))
			{
				std::vector<Person> contacts;
				std::ifstream reader("ContactList.txt", std::ios::in);

				if (reader.is_open())
				{
					// read data from ContactList and create Persons
					// to fill the fill the file after deletion
					// ignores the selected contact
					std::string fname, lname, email, phone_number;
					for (int i = 0; i < num_of_contacts; i++)
					{
						reader >> fname >> lname >> email >> phone_number;
                                                
                                                // i is always 1 less than the actual selection number
						if ((i + 1) != selection)
							contacts.push_back(Person(fname, lname, email, phone_number));
					}

					num_of_contacts--;
					reader.close();
				}
				else
				{
					std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***";
					std::cout << "\n\t\t\t\t\t"; system("PAUSE");
				}
				
				std::ofstream writer("ContactList.txt", std::ios::out);

				if(writer.is_open())
				{
					// Fills the file with the data from the contact vector
					for (int i = 0; i < num_of_contacts; i++)
					{
						writer << contacts[i].getFirstName() << " "
							   << contacts[i].getLastName() << " "
							   << contacts[i].getEmail() << " "
							   << contacts[i].getNumber() << std::endl;
					}

					std::cout << "\n\n\t\t\t\t\t----------------------------";
					std::cout << "\n\t\t\t\t\t|   Deletion Successfull   |";
					std::cout << "\n\t\t\t\t\t----------------------------";

					writer.close();
				}
				else
				{
					std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***";
					std::cout << "\n\t\t\t\t\t"; system("PAUSE");
				}

				// FILE READING/WITING TO TMP FILE IMPLEMENTATION
				/*std::ifstream reader("ContactList.txt", std::ios::in);
				std::ofstream writer("tmp_contacts.txt", std::ios::out);

				if (reader.is_open())
				{
					std::string fname, lname, email, phone_num;

					for (int i = 1; i <= num_of_contacts; i++)
					{
						if (i != selection)
						{
							reader >> fname >> lname >> email >> phone_num;
							writer << fname << " "
								   << lname << " "
								   << email << " "
								   << phone_num << std::endl;
						}
						else
						{
							reader >> fname >> lname >> email >> phone_num;
						}
					}

					num_of_contacts -= 1;

					reader.close();
					writer.close();

					writer.open("ContactList.txt", std::ios::out);
					reader.open("tmp_contacts.txt", std::ios::in);

					for (int i = 1; i <= num_of_contacts; i++)
					{
						reader >> fname >> lname >> email >> phone_num;
						writer << fname << " " 
							   << lname << " " 
							   << email << " "
							   << phone_num << std::endl;
					}

					std::cout << "\n\n\t\t\t\t\t----------------------------";
					std::cout << "\n\t\t\t\t\t|   Deletion Successfull   |";
					std::cout << "\n\t\t\t\t\t----------------------------";
				}
				else
				{
					std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***";
					std::cout << "\n\t\t\t\t\t"; system("PAUSE");
				}*/
			}
			else if (selection == 0)
			{
				std::cout << "\n\n\t\t\t\t\t-----------------------------------------";
				std::cout << "\n\t\t\t\t\t|   Canceling Request To Delete Entry   |";
				std::cout << "\n\t\t\t\t\t-----------------------------------------";
			}
			else
			{
				valid = false;

				std::cout << "\n\n\t\t\t\t\t*** [ Error! Invalid Selection ] ***";
				std::cout << "\n\t\t\t\t\t"; system("PAUSE");
			}
		}
	} while ((!valid) && (num_of_contacts != 0));
}

C++ Class Constructor

27 December 2015 - 03:09 PM

Hello,

 

So I am working on a simple phonebook app using file reading/writing, but in my Phonebook class constructor I am having issues. For some reason it is not allowing me to pass a string argument to the constructor. I took out the argument in the definition and declaration and it compiled fine and ran so I know that is where the issue is.

 

The error message is "C2664    'Phonebook::Phonebook(Phonebook &&)': cannot convert argument 1 from 'std::string' to 'const Phonebook &'    MyPhonebook    c:\users\brandon\documents\visual studio 2015\projects\myphonebook\myphonebook\main.cpp    30" and it doesn't make any sense to me. I googled the error message and I am passing a string to the constructor not any other type. I also get another error message saying "C4430    missing type specifier - int assumed. Note: C++ does not support default-int    MyPhonebook    c:\users\brandon\documents\visual studio 2015\projects\myphonebook\myphonebook\person.h    14"
 

Can someone please help me see what is happening? I would greatly appreciate it!

 

Phonebook.h

#pragma once 

#include "LibIncludes.h"

class Phonebook
{
public:
	Phonebook(string tmp_pb_name);
	void addEntry();
	void deleteEntry();
	void searchByFirstName() const;
	void searchByNumber() const;
	void displayAllEntries() const;
	void clearAllEntries();
	int mainMenu();
private:
	string phonebook_name;
};

Phonebook.cpp

///////////////////////////////////////
//
//   Phonebook definitions   
//
///////////////////////////////////////

#include "LibIncludes.h"

Phonebook::Phonebook(string tmp_pb_name)
{
	phonebook_name = tmp_pb_name;
}

//--------------------------------------------------------------------

int Phonebook::mainMenu()
{
	int option = 0;

	do
	{
		system("CLS");

		cout << "\n\n\t\t-----" << phonebook_name << " Phonebook-----";
		cout << "\n\t\t|";
		cout << "\n\t\t|\t[1] Create New Entry";
		cout << "\n\t\t|\t[2] Delete Entry";
		cout << "\n\t\t|\t[3] Display ALL Entries";
		cout << "\n\t\t|\t[4] Search By FIRST Name";
		cout << "\n\t\t|\t[5] Search by PHONE NUMBER";
		cout << "\n\t\t|\t[6] Clear ALL Entries";
		cout << "\n\t\t|\t[7] Exit Your Phonebook";
		cout << "\n\t\t|----------------------------------------------";

		cout << "\n\n\t\t> ";
		cin >> option;

		if (option < 1 || option > 7)
		{
			cout << "\n\t\t*** [ Error! Option Out Of Range! ] ***\n";
			system("PAUSE");
		}
	} while (option < 1 || option > 7);

	return option;
}

//--------------------------------------------------------------------

void Phonebook::addEntry()
{
	
}

//--------------------------------------------------------------------

void Phonebook::displayAllEntries() const
{

}

//--------------------------------------------------------------------

void Phonebook::clearAllEntries()
{

}

//--------------------------------------------------------------------

void Phonebook::deleteEntry()
{

}

//--------------------------------------------------------------------

void Phonebook::searchByFirstName() const
{

}

//--------------------------------------------------------------------

void Phonebook::searchByNumber() const
{

}

Main.cpp

///////////////////////////////////////
//
//   Basic phonebook app that
//   uses writing and reading
//   from files for the data
//   entries
//
//////////////////////////////////////

#include "LibIncludes.h"

string setPhoneBookName()
{
	string name; 

	cout << "\n\n\n\n\t\t\t\t-----Please Enter In Your Desired Phonebook Name-----";
	cout << "\n\t\t\t\t> ";
	cin >> name;

	return name;
}

//---------------------------------------------------------------------------------------

int main()
{
	int user_option = 0;
	bool exit = false;

	Phonebook myBook(setPhoneBookName());

	while (user_option != 7)
	{
		while (!exit)
		{
			user_option = myBook.mainMenu();

			switch (user_option)
			{
			case 7:
				cout << "\n\n\t\t---------------Goodbye---------------\n";
				cout << "\t\t";
				system("PAUSE");
				exit = true;
				break;
			default:
				cout << "\n*** [ Invalid Option! ] ***\n";
			}
		}
	}

	return 0;
}

LibIncludes.h

/////////////////////////////////////
//
//   All header files needed
//
/////////////////////////////////////

#pragma once

#include <iostream>
#include <string>
#include <fstream>

#include "Person.h"
#include "Phonebook.h"

using namespace std;

C++ VirtualFunctions [SOLVED]

23 December 2015 - 09:18 PM

Hello,

 

I am messing around with inheritance and I was doing a simple example using it, but for some reason it is not working like I expected it to. When I run the code, the greet() method from the Animal base class is being called on both objects, even though I have it as a virtual function. I thought this would allow the child class to behave differently when used with pointers. Could anyone please help me see what I am doing incorrectly or maybe misunderstood?

/////////////////////////////////
//
//   Random C++ tests on
//   concepts and ideas
//
/////////////////////////////////

#include <iostream>
#include <string>
#include <iterator>
#include <vector>

using namespace std;

class Animal
{
public:
	Animal(string tmp_name)
	{
		name = tmp_name;
	}

	virtual void greet()
	{
		cout << "I am " << name << ", and I am Animal" << endl;
	}
protected:
	string name;
};

class Bird : public Animal 
{
public:
	Bird(string tmp_name) : Animal(tmp_name) {};

	void greet()
	{
		cout << "I am " << name << " and I am a Bird" << endl;
	}
};

//////////////////////////////////////////////////////////////////
//   MAIN
//////////////////////////////////////////////////////////////////

int main()
{
	Animal * steve = new Bird("Steve");
	Animal * david = new Animal("David");

	vector<Animal> animal_list = { *steve, *david };

	for (vector<Animal>::iterator itr = animal_list.begin(); itr != animal_list.end(); itr++)
	{
		itr->greet();
	}

	cin.get();

	return 0;
}

PARTNERS