I'm having this problem where I keep getting the bad access warning. I see this typically spurs from exceeding the array bounds but in this case I don't see how that can be the problem when I have the condition subscript >= 0 && subscript < size
.
I've played around with the program a little bit and I cant seem to find a fix. I'm going to paste in a few code blocks where I think the issue may be coming from and if you guys can take a look and maybe point me in the right direction that would be great!
Header file.
class ArrayClass{
friend ArrayClass operator +( const ArrayClass &, const ArrayClass & );
friend ArrayClass operator +( const ArrayClass &, const float );
friend ostream & operator << ( ostream &, const ArrayClass & );
friend istream & operator >> ( istream &, ArrayClass &);
private:
float *floatArray;
int size;
public:
ArrayClass(){ init(); }
ArrayClass(int s = 0){
init();
size = s;
floatArray = new float[size];
}
void init();
ArrayClass( const ArrayClass& );
void operator=( const ArrayClass& );
~ArrayClass();
const int operator [] ( int ) const;
// Various other methods. Output, getter/setter, etc.
}
Source file. (Possible causes)
const int ArrayClass::operator [] (int subscript) const{
if(subscript >= 0 && subscript < size)
return floatArray[ subscript ];
return 0;
}
ArrayClass operator +( const ArrayClass& arr1, const ArrayClass& arr2){
ArrayClass temp_arr(arr1.size);
for (int i = 0; i < arr1.size; i++){
temp_arr.floatArray[i] = arr1[i] + arr2[i];
}
return temp_arr;
}
ostream& operator << ( ostream & out, const ArrayClass &arr ){
for (int i = 0; i < arr.size; i++)
out << arr.floatArray[i];
return out;
}
ArrayClass:: ArrayClass(const ArrayClass& that){
// Initialize state
init();
// Assigns input to self
*this = that;
}
void ArrayClass::operator=(const ArrayClass& that){
if (this != &that){
// Copy static varibles
floatArray = that.floatArray;
size = that.size;
// Deletes existing memory
if (floatArray)delete [] floatArray;
// Allocate memory for object
if(size)
floatArray = new float[size];
else
floatArray = NULL;
// Copy dynamic memory
for(int i = 0; i < size; ++i)
floatArray[i] = that.floatArray[i];
}
}
ArrayClass:: ~ArrayClass(){
if (floatArray) delete [] floatArray; //malloc: *** error for object
}
And then in the main I just enter an array size, add them result = arr1 + arr2;
and print cout<< result;
UPDATE: Ok so i took the comments into mind and redid a lot of this and put up some updated code, but now I'm getting a new malic error (pointer being freed was not allocated). I know this was marked as a duplicate but I think the problem has shifted to a slightly so if you can take another look that would be extremely helpful. Side note: If i comment out the destructor I get the correct results but id like to have it in there.