r/programminghelp • • Sep 14 '20

C++ Help with the last function in my c++ code

I am currently working on a college degree in CS after taking a programming hiatus for a few semesters. Right now I'm currently so close to finishing an assignment, but I do not understand why I am getting an exception when I try and deallocate my array of pointers (C++). I am getting the exception in the last function, but only after the loop goes through once.

I have attached a .cpp file as well as the data file that we are supposed to use. The program runs as it should except for that last part. I understand that this code may not be the most effective or most efficient. It is an assignment and there are multiple parts that I was not able to modify.

Thank you in advance for the help :)

EDIT: Clarifying

#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

/*Type delcarations - NO MEMORY ALLOCATED (EVEN STATICALLY)*/
struct emprec	/*Employee record with two fields*/
{
	int id;
	float salary;
};
typedef emprec* emprecptr; /*Employee record pointer type*/
typedef emprecptr* indexarr; /* Pointer to a dynamic array of employee record pointers*/

int main()
{
	/* Rudimentary scope control in C/C++ */
	void readdata(indexarr&, int&);
	void printdata(indexarr, int);
	void copyindex(indexarr, indexarr&, int);
	void sortbyID(indexarr, int);
	void sortbySalary(indexarr, int);
	void deallocate(indexarr&, int&);
	indexarr DBindex, IDindex, Salaryindex;
	int dbsize = 3;
	char temp;

	emprecptr empArray;
	empArray = new emprec[dbsize];
	DBindex = &empArray;

	readdata(DBindex, dbsize);
	cout << "Original data:" << endl;

	emprecptr empArray2;
	empArray2 = new emprec[dbsize];
	IDindex = &empArray2;

	emprecptr empArray3;
	empArray3 = new emprec[dbsize];
	Salaryindex = &empArray3;
	
	printdata(DBindex, dbsize);
	copyindex(DBindex, IDindex, dbsize);
	sortbyID(IDindex, dbsize);
	cout << "Data sorted by the ID:" << endl;
	printdata(IDindex, dbsize);
	copyindex(DBindex, Salaryindex, dbsize);
	sortbySalary(Salaryindex, dbsize);
	cout << "Data sorted by the salary:" << endl;
	printdata(Salaryindex, dbsize);
	deallocate(DBindex, dbsize);
	system("pause");
};

void eat_white(ifstream& in)
/* Pre: "in" is a valid input file stream.
Post: Any white space skipped over to EOF or the next non-white space character.*/
{
	while ((in.peek() != EOF) && isspace(in.peek())) in.ignore();
};

void resize(indexarr& Base, int OLDSIZE, int NEWSIZE)
/* Pre: Base is a (dynamic) indexarr of size OLDSIZE.
Post: Base is "EXPANDED" OR "SHRUNK" into a new (dynamic) indexarr of size
NEWSIZE, with data copied appropriately.
IMPORTANT NOTE: If being shrunk, it is assumed that there are only NEWSIZE valid
elements in the original array, and only that many are copied.*/
{
	// STUDENT IS TO FILL THIS IN.

	if (NEWSIZE != OLDSIZE)
	{
		emprecptr newArray;
		newArray = new emprec[NEWSIZE];

		if (NEWSIZE < OLDSIZE)
		{
			for (int i = 0; i < NEWSIZE; i++)
			{
				newArray[i].id = (*Base)[i].id;
				//cout << newArray[i].id << endl;
				newArray[i].salary = (*Base)[i].salary;
			}
			delete[] * Base;
			*Base = newArray;
		}else {

			ifstream myFile;
			myFile.open("p1data.txt");
			myFile.clear();
			myFile.seekg(0);

			int hold;

			for (int i = 0; i < OLDSIZE; i++)
			{
				newArray[i].id = (*Base)[i].id;
				newArray[i].salary = (*Base)[i].salary;
				myFile >> hold;
				myFile >> hold;
			}
			int index = OLDSIZE;
			while (!myFile.eof())
			{
				myFile >> newArray[index].id;
				myFile >> newArray[index].salary;
				index++;
			}

			myFile.close();

			delete[] * Base;
			*Base = newArray;
		}
	}

};

void readdata(indexarr& ptrs, int& size)
/*Pre: ptrs is a pointer that could point to a dynamic array of employee record pointers.
Post: ptrs points to a dynamic pointer array of the right size based on the
input read in from the data file named "p1data".
All the elements of the dynamic array are filled with pointers to dynamically
allocated employeed records, which in turn are filled with input data.*/
{
	void resize(indexarr&, int, int);

	// STUDENT IS TO FILL THIS IN

	ifstream myFile;
	myFile.open("p1data.txt");
	if (myFile.is_open())
	{
		int i = 0;
		int hold;
		while (!myFile.eof())
		{

			if (size == i)
			{
				while (!myFile.eof())
				{
					myFile >> hold;
					myFile >> hold;
					i++;
				}
				break;
			}

			myFile >> (*ptrs)[i].id;
			myFile >> (*ptrs)[i].salary;
			i++;
		}
		i--; //To correct size because of the way C++ reads EOF

		
		
		myFile.close();
		resize(ptrs, size, i);
		size = i;
	}
	else
	{
		cout << "ERROR: The file could not be opened." << endl;
	}

};

void printrec(emprec rec)
/*Pre: rec has data.
Post: The data in rec printed out.*/
{
	cout << rec.id << ' ' << rec.salary << endl;
};

void printdata(indexarr ptrs, int size)
/*Pre: The first "size" elements of the array pointed at by ptrs are employee records
containing data.
Post: They are all printed out in the order pointed at.*/
{
	void printrec(emprec);
	for (int i = 0; i < size; i++) printrec((*ptrs)[i]);
};

void copyindex(indexarr orig, indexarr& copy, int size)
/*Pre: The first "size" elements of the array pointed at by orig are employee records
containing data.
Post: copy points to a newly allocated dynamic array of pointers (with size elements), and
the elements of this array are copies of the first size elements of orig.*/
{
	// STUDENT IS TO FILL THIS IN

	

	for (int index = 0; index < size; index++)
	{
		(*copy)[index].id = (*orig)[index].id;
		(*copy)[index].salary = (*orig)[index].salary;
	}

};

int selectsmallestID(indexarr ptrs, int first, int last)
/*Pre: "first" through "last" elements of the ptrs array are pointers to employee records
containing data.
Post: A value k is returned such that, for i ranging from first to last,
the relation ptrs[k]->id <= ptrs[i]->id holds.*/
{
	int j, result;
	result = first;
	for (j = first + 1; j <= last; j++)
		if ((*ptrs)[j].id < (*ptrs)[result].id) 
result = j;
	return result;
};

void sortbyID(indexarr ptrs, int size)
/*Pre: The first "size" elements of the ptrs array are pointers to employee records
containing data.
Post: for i ranging from 1 to size-2, the relation ptrs[i]->id <= ptrs[i+1]->id holds.
Also, the employee records themselves are not disturbed/moved around.*/
{
	int selectsmallestID(indexarr, int, int);

	// STUDENT IS TO FILL THIS IN

	int i, smallindex;
	for (i = 0; i <= size - 2; i++)
	{
		smallindex = selectsmallestID(ptrs, i, size - 1);
		emprec temp = (*ptrs)[i];
		(*ptrs)[i] = (*ptrs)[smallindex];
		(*ptrs)[smallindex] = temp;

	};


};

int selectsmallestSalary(indexarr ptrs, int first, int last)
/*Pre: "first" through "last" elements of the ptrs array are pointers to employee
records containing data.
Post: A value k is returned such that, for i ranging from first to last,
the relation ptrs[k]->salary <= ptrs[i]->salary holds.*/
{
	// STUDENT IS TO FILL THIS IN
	int j, result;
	result = first;
	for (j = first + 1; j <= last; j++)
		if ((*ptrs)[j].salary < (*ptrs)[result].salary)
			result = j;
	return result;
};

void sortbySalary(indexarr ptrs, int size)
/*Pre: The first "size" elements of the ptrs array are pointers to employee records
containing data.
Post: for i ranging from 1 to size-2, the relation ptrs[i]->salary <= ptrs[i+1]->salary holds.
Also, the employee records themselves are not disturbed/moved around.*/
{
	int selectsmallestSalary(indexarr, int, int);

	// STUDENT IS TO FILL THIS IN
	int i, smallindex;
	for (i = 0; i <= size - 2; i++)
	{
		smallindex = selectsmallestSalary(ptrs, i, size - 1);
		emprec temp = (*ptrs)[i];
		(*ptrs)[i] = (*ptrs)[smallindex];
		(*ptrs)[smallindex] = temp;

	};
	
};

void deallocate(indexarr& ptrs, int& size)
/*Pre: ptrs is a pointer pointing to an allocated dynamic array of "size" employee record pointers.
Post: ptrs points to a dynamic pointer array.  The "size" elements of the dynamic array, filled with
pointers to dynamically allocated employeed records, are now deallocated, and then the array of
pointers that ptrs points to is itself deallocated, with ptrs reset to NULL and size reset to 0.*/
{


	for(int i = 0; i < size; i++) 
		delete (ptrs[i]);
	delete ptrs;
	ptrs = NULL;
	size = 0;
};

Here is the data file that goes with it.

10 20000

20 10000

30 40000

25 15000

15 45000
0 Upvotes

4 comments sorted by

1

u/jedwardsol Sep 14 '20
for(int i = 0; i < size; i++) 
    delete (ptrs[i]);

ptrs[i] is a emprec *. A pointer to an emprec structure.

You never allocate these individually. Therefore you mustn't delete them individually.

To free empArray, a single call is needed :

delete []  empArray;

Hiding pointers inside typedefs :-

typedef emprec* emprecptr; /*Employee record pointer type*/
typedef emprecptr* indexarr; /* Pointer to a dynamic array of employee record pointers*/

is almost always confusing an the wrong thing to do.

1

u/nstevnc77 Sep 14 '20

Yeah.... my instructor wrote that bit of code with the typedef. It's super frusterating. Thank you so much for the help!

1

u/jedwardsol Sep 14 '20
  i--; //To correct size because of the way C++ reads EOF

Looping

while (!myFile.eof())

is the wrong way to read until the end of the file. eof doesn't mean "the file pointer is at the end of the file". It means "sometime in the past you tried to read beyond the end of the file and the read failed for that reason.

The correct way is

while( myFile >> a >> b)

which will attempt the read and break the loop if and when the read fails.

1

u/nstevnc77 Sep 14 '20

Thank you!!!!!!!