Hey, My code works perfectly for this cash register program that I've made except for the dynamic memory. All sales are stored as an Array of Class Type 'Sale', here are the functions with issues:
Ring Up:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void RingUpSale(ItemType ITEM, double PRICE);//PROTOTYPE IN PUBLIC OF REGISTER CLASS
void Register::RingUpSale(ItemType ITEM, double PRICE)
{
if(index == MaxArray)//Grows array if Index is equal to the current Maximum.
{
GrowArray(saleArray, MaxArray);
MaxArray += ARRAYSIZE;
}
saleArray[index].MakeSale(ITEM, PRICE);
if(ITEM == CREDIT)
balance -= saleArray[index].Total();
else
balance += saleArray[index].Total();
saleArray[index].Display();
index = index++;
}
Sale * GrowArray(Sale* oldArray, constint S);//Prototype
Sale * ShrinkArray(Sale* oldArray, constint S);//Protoype
Sale * GrowArray(Sale* oldArray, constint S)//Similar to class provided code
{
static Sale* temp;
temp = new Sale[S+ARRAYSIZE];
for(int i = 0; i < S; i++)//Copies Data
temp[i]= oldArray[i];
delete [] oldArray;
cout << "Increased register size to: " << S+ARRAYSIZE << endl;
return temp;
}
Sale * ShrinkArray(Sale* oldArray, constint S)
{
static Sale* temp;
temp = new Sale[S-ARRAYSIZE];
for(int i = 0; i < S; i++)//Copies Data
temp[i]= oldArray[i];
delete [] oldArray;
cout << "Decreased register size to: " << S-ARRAYSIZE << endl;
return temp;
}
I'm almost 100% sure it's not returning correctly, because when I jump into the next sale after Grow Array is activated, and after my debugger shows saleArray with 'garbage numbers' in it. I get an error related to the Heap.
This may be due to a corruption of the heap, which indicates a bug in cashregister.exe or any of the DLLs it has loaded.
It crashes right after when it calls a simple print function, which makes me believe, again, that it's not returning correctly.
This is my first time working with Dynamic Memory, any help/advice would be greatly appreciated!!!
void GrowArray(Sale* oldArray, constint S)//Similar to class provided code
{
static Sale* temp;
temp = new Sale[S+ARRAYSIZE];
for(int i = 0; i < S; i++)//Copies Data
temp[i]= oldArray[i];
delete [] oldArray;
oldArray = temp; //This is new
cout << "Increased register size to: " << S+ARRAYSIZE << endl;
return; //This is changed to match return type
}
And make the same changes to ShrinkArray also. Temp goes out of scope when this function returns. Don't want to return that.
With further inspection, when I print out the data, all data from before the move is lost, and is replaces with garbage numbers, however the new data is OK.
In line 6 of the snippet in the OP of Register::RingUpSale:
GrowArray(saleArray, MaxArray);
The value returned from GrowArray is not stored. And the value held by saleArray is invalid after the call. Returning temp was correct, however, you must do something with the value returned. Like assign it to saleArray.