Invalid allocation runtime error - c++

I have to replicate a vector class using an int and overload a bunch of operators. How ever every time I try to use the +, -, or / operator I get a runtime error which says invalid allocation size: 4294967295 bytes. Any feed back on how I can improve my code is welcome as well.
my code:
myArray.h
#include<iostream>
using namespace std;
class myArray{
private:
int *A;
int lenght;
int maxSize;
public:
myArray(){lenght = 0; maxSize = 0; A = new int[maxSize];}
myArray(int s){maxSize = s; lenght = 0; A = new int[maxSize];}
myArray(const myArray &M);
~myArray(){delete[] A;}
const int getMaxSize(){return maxSize;}
const int getLenght(){return lenght;}
const myArray& operator +(const myArray& A);
const myArray& operator -(const myArray A);
const int operator *(const myArray& A);
const myArray& operator /(const myArray A);
const myArray& operator +(int A);
const myArray& operator -(int A);
const int operator *(int A);
const myArray operator /(int A);
const myArray operator ++();
const myArray operator ++(int);
const myArray operator --();
const myArray operator --(int);
myArray operator -();
int operator [](int ind) const;
myArray& operator =(const myArray& rho);
void push(int n);
int pop();
void insert(int n, int pos);
int remove(int pos);
void resize(int newSize);
};
myException.h
#include<iostream>
#include<exception>
#include<string>
using namespace std;
class myException: public exception
{
private:
int code;
string reason;
public:
myException(){code = 0; reason = "Unknown";}
myException(int c, string r){code = c; reason = r;}
friend ostream& operator <<(ostream& outputStream, const myException A);
};
ostream& operator <<(ostream& outputStream, const myException A)
{
outputStream << "Code: " << A.code << " Reason: " << A.reason << endl;
return outputStream;
}
myArray.cpp
#ifndef MYARRAY_H
#define MYARRAY_H
#include "myArray.h"
#include "myException.h"
//Copy contructor
myArray::myArray(const myArray &M)
{
maxSize = M.maxSize;
lenght = M.lenght;
A = new int[maxSize];
for(int i = 0; i < M.lenght; i++)
A[i] = M.A[i];
}
//Adds the elements of the array with each other and returns the result
const myArray& myArray::operator +(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = A[i] + secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Subtracts the elements of the array with each other and returns the result
const myArray& myArray::operator -(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] - secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Gets the dot product of 2 vectors
const int myArray::operator *(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Divides the elements of the array with each other and returns the result
const myArray& myArray::operator /(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] / secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Adds the elements of the array with an int and returns the result
const myArray& myArray::operator +(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] + A;
return result;
}
//Subtracts the elements of the array with an int and returns the result
const myArray& myArray::operator -(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] - A;
return result;
}
//Gets the dot product of a vector multiplied by an int
const int myArray::operator *(int A)
{
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * A;
return result;
}
//Divides the elements of the array with an int and returns the result
const myArray myArray::operator /(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] / A;
return result;
}
//increments every element in the array by 1(Pre-increment)
const myArray myArray::operator ++()
{
for(int i = 0; i < lenght; i++)
++A[i];
return *this;
}
//increments every element in the array by 1(Post-increment)
const myArray myArray::operator ++(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]++;
return temp;
}
//decrements every element in the array by 1(Pre-decrement)
const myArray myArray::operator --()
{
for(int i = 0; i < lenght; i++)
--A[i];
return *this;
}
//decrements every element in the array by 1(Post-decrement)
const myArray myArray::operator --(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]--;
return temp;
}
//Makes every element in the array negative
myArray myArray::operator -()
{
for(int i = 0; i < lenght; i++)
A[i] = -A[i];
return *this;
}
//returns the number in the array using []
int myArray::operator [](int ind) const
{
try
{
if(ind > lenght)
throw myException(60, "Array index out of bounds");
return A[ind];
}
catch(myException& e)
{
cout << e;
}
}
//Assignment operator
myArray& myArray::operator=(const myArray& B)
{
delete [] A;
A = new int[B.maxSize];
lenght = B.lenght;
maxSize = B.maxSize;
for(int i = 0; i < B.lenght; i++)
{
A[i] = B.A[i];
}
return (*this);
}
//pushes the value inserted to the next available spot in the array
void myArray::push(int n)
{
try
{
if(lenght == maxSize)
throw myException(30, "Not enough space");
if(lenght == 0)
{
A[0] = n;
lenght++;
}
else
{
for(int i = 0; i < lenght; i++)
{
if(i+1 == lenght)
{
A[i+1] = n;
lenght++;
break;
}
}
}
}
catch(myException& e)
{
cout << e;
}
}
//Removes the last element in the array and returns it
int myArray::pop()
{
try
{
if(lenght <= 0)
throw myException(60, "Array index out of bounds");
int temp = A[lenght - 1];
A[lenght - 1] = NULL;
lenght--;
return temp;
}
catch(myException& e)
{
cout << e;
}
}
inserts an element at the specified position
void myArray::insert(int n, int pos)
{
try
{
if(pos > lenght)
throw myException(60, "Array index out of bounds");
for(int i = 0; i <= lenght; i++)
{
if(i == pos)
{
A[i-1] = n;
}
}
}
catch(myException& e)
{
cout << e;
}
}
//removes an element at a specified position an returns the value.
int myArray::remove(int pos)
{
try
{
if(pos < 0 || (pos > lenght -1))
throw myException(50, "Invalid Position");
int temp = A[pos];
A[pos] = NULL;
for(int i = pos; i < lenght; i++)
{
A[i] = A[i+1];
}
return temp;
}
catch(myException& e)
{
cout << e;
}
}
//Re sizes the entire array
void myArray::resize(int newSize)
{
int *B;
B = new int[newSize];
maxSize = newSize;
for(int i = 0; i < lenght; i++)
B[i] = A[i];
delete[] A;
A = B;
}
#endif
This is just a dummy main to test everything on the myArray class
main.cpp
#include "myArray.h"
int main()
{
int num;
myArray vector1;
myArray vector2(5);
myArray vector3;
vector1.resize(5);
//cout << "Max Size: " << vector1.getMaxSize() << endl;
for(int i = 0; i < 4; i++)
{
cin >> num;
vector1.push(num);
}
for(int i = 0; i < 4; i++)
{
cin >> num;
vector2.push(num);
}
vector3 = vector1 + vector2;
for(int i = 0; i < 4; i++)
cout << vector3.pop() << endl;
}

You create dynamic array with zero size in default constructor.
But in push method you try to set value to it if it's length is zero.
In C++ standard it says:
The effect of dereferencing a pointer returned as a request for zero
size is undefined.
You can only delete it. Fix your push method

Related

how to put all the numbers in the white boxes on the chessboardArray, in C++?

I wrote the following code for creating a chessboard using 2D Arrays in C++ :
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
Here is the ChessBoardArray class:
class ChessBoardArray
{
protected:
class Row
{
public:
Row(ChessBoardArray &a, int i): cba(a), row(i){}
int & operator[] (int i) const
{
return cba.select(row, i);
}
private:
ChessBoardArray &cba;
int row;
};
class ConstRow
{
public:
ConstRow(const ChessBoardArray &a, int i): cba(a), row(i){}
int operator[] (int i) const
{
return cba.select(row, i);
}
private:
const ChessBoardArray &cba;
int row;
};
unsigned int my_size;
int my_base;
int *data;
The loc function is for finding the location of an element. It corresponds the elements of the 2D array to the corresponding position.
unsigned int loc(int i, int j) const throw(out_of_range)
{
int di = i - my_base, dj = j - my_base;
if(di < 0 || di >= my_size || dj < 0 || dj >= my_size) throw out_of_range("invalid index");
return di * my_size + dj;
}
public:
ChessBoardArray(unsigned size = 0, unsigned base = 0)
{
my_size = size;
my_base = base;
data = new int[my_size * my_size];
}
ChessBoardArray(const ChessBoardArray &a)
{
my_size = a.my_size;
my_base = a.my_base;
data = new int[my_size * my_size];
for(int i = 0; i < my_size*my_size; i++) data[i] = a.data[i];
}
~ChessBoardArray()
{
delete [] data;
}
ChessBoardArray & operator= (const ChessBoardArray &a)
{
this -> ~ChessBoardArray();
my_size = a.my_size;
my_base = a.my_base;
data = new int[my_size * my_size];
for(int i = 0; i < my_size*my_size; i++) data[i] = a.data[i];
return *this;
}
int & select(int i, int j)
{
return data[loc(i, j)];
}
int select(int i, int j) const
{
return data[loc(i, j)];
}
const Row operator[] (int i)
{
return Row(*this, i);
}
const ConstRow operator[] (int i) const
{
return ConstRow(*this, i);
}
friend ostream& operator<< (ostream &out, const ChessBoardArray &a)
{
for(int i = a.my_base; i <= a.my_size; i++)
{
for(int j = a.my_base; j <= a.my_size; j++)
{
out << setw(4) << a.data[a.loc(i, j)];
}
out << endl;
}
return out;
}
};
The condition for a number to be in a white box is i%2 == j%2. Where should i add the condition in my code?
I tried putting it inside the loc function but it got me some errors.

Dynamic allocation of a matrix using classes returns something like "21.684268-3121"

class Vector {
protected:
unsigned int dim;
float *a;
public:
Vector() {
a = NULL;
dim = 0;
}
Vector(const unsigned int& x) {
dim = x;
a = new float[dim];
for (unsigned int index = 0; index < x; index++) {
cin >> a[index];
}
}
Vector(const float *init, const unsigned int& size) {
if (init) {
dim = size;
a = new float[size];
for (unsigned int index = 0; index < size; index++) {
a[index] = init[index];
}
}
}
void initVector(const float *init, const unsigned int& size) {
if (init) {
dim = size;
a = new float[size];
for (unsigned int index = 0; index < size; index++) {
a[index] = init[index];
}
}
}
void initVector(const unsigned int& size) {
dim = size;
a = new float[dim];
for (unsigned int index = 0; index < size; index++) {
cin >> a[index];
}
}
unsigned int getDim() {
return dim;
}
float operator[](unsigned int pos) {
return a[pos];
}
~Vector() {
delete[] a;
}
friend class Matrice;
friend istream& operator>>(istream&, Vector&);
};
class Matrice {
protected:
Vector *v;
public:
Matrice() {
v = NULL;
}
Vector operator[](int pos) {
return v[pos];
}
friend istream& operator>>(istream&, Matrice&);
};
class Matrice_oarecare : public Matrice
{
protected:
unsigned int linii;
public:
Matrice_oarecare() {
linii = 0;
}
Matrice_oarecare(int coloane, int linii) {
this->linii = linii;
v = new Vector[linii];
for ( int index = 0; index < linii; index++) {
cin >> v[index]; //Asta apeleaza >> pentru Vector, care citeste toate numerele din sir
}
}
friend istream& operator>>(istream& in, Matrice_oarecare&a);
friend ostream& operator<<(ostream& out, Matrice_oarecare&a);
};
class Matrice_patratica : public Matrice {
unsigned int dim;
public:
Matrice_patratica() {
v = NULL;
dim = 0;
}
Matrice_patratica(unsigned int dim) {
this->dim = dim;
v = new Vector[dim];
for (unsigned int index = 0; index < dim; index++) {
float *init = new float[dim];
for (unsigned index2 = 0; index2 < dim; index2++)
cin >> init[index];
v[index].initVector(init, dim);
}
}
friend ostream& operator<<(ostream&, Matrice_patratica&);
};
istream& operator>>(istream& in, Vector& v) {
in >> v.dim;
v.a = new float[v.dim];
for (unsigned int i = 0; i < v.dim; i++)
in >> v.a[i];
return in;
}
ostream& operator<<(ostream& os, Matrice_oarecare& a) {
for (unsigned indexI = 0; indexI < a.v->getDim(); indexI++) {
for (unsigned indexJ = 0; indexJ < a.linii; indexJ++) {
os << a[indexI][indexJ];
}
}
return os;
}
ostream& operator<<(ostream& os, Matrice_patratica& a) {
for (unsigned indexI = 0; indexI < a.dim; indexI++) {
for (unsigned indexJ = 0; indexJ < a.dim; indexJ++) {
os << a[indexI][indexJ];
}
}
return os;
}
int main() {
Matrice_oarecare c(2,2);
cout << c << endl;
return 0;
}
I have some problems while trying to dynamic allocate a matrix. Whatever I write, it return something like '21.3244141e-48198' and idk why. I think that the problem might be either the overloaded << operator, or one inheritance.
The 'Matrice_oarecare' and 'Matrice_patratica' have to inherit the Matrice class, and I have to create them using the Vector class.

My own vector class

I am trying to create my own vector class. I want to overload the basic features of STL vector. My code is compiling by after testing it, a message "segmentation fault(core dumped is)" is shown. Could you show me where I can improve my code. Thank you in advance!
#include<iostream>
#include<fstream>
using namespace std;
class Vector
{
public:
Vector();
Vector(const Vector& vect);
~Vector();
Vector& operator =(const Vector& vect);
void insert(double element);
bool operator ==(const Vector& vect);
Vector& operator +(const Vector& vect);
Vector& operator -(const Vector& vect);
Vector& operator *(const Vector& vect);
int size();
double operator[](int num);
friend istream& operator >>(istream& input, Vector& vect);
friend ostream& operator <<(ostream& output, Vector& vect);
private:
double* data;
int num;
int max;
};
Vector:: Vector()
{
double* data = NULL;
int num = 0;
int max = 0;
}
Vector::Vector(const Vector& vect)// not sure if its correct
{
data = new double[vect.max];
memcpy(data, vect.data, sizeof(double) * vect.num);
num = vect.num;
max = vect.max;
}
Vector::~Vector()
{
if(data)
{
delete[] data;
data = 0;
}
}
void Vector:: insert(double element)
{
if(num < max)
{
*(data + num) = element;
}
else
{
double *tmp = new double[num * 2];
delete[] data;
*(data + num) = element;
max *= 2;
}
num++;
}
Vector& Vector:: operator = (const Vector& vect)// highly unlikely to be correct
{
if(this != &vect)
{
if(data)
{
delete[] data;
data = 0;
}
max = vect.max;
data = new double[max];
for(int i = 0; i < num; i++)
{
this->data[i] = vect.data[i];
}
}
return *this;
}
bool Vector:: operator ==(const Vector& vect)
{
bool isEqual = true;
if(this->num != vect.num)
{
isEqual = false;
}
for(int i = 0; i < num; i++)
{
if(this->data[i] != vect.data[i] )
{
isEqual = false;
}
}
return isEqual;
}
Vector& Vector:: operator +(const Vector& vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) + *(vect.data + i));
}
return result;
}
Vector& Vector:: operator -(const Vector& vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) - *(vect.data + i));
}
return result;
}
Vector& Vector::operator*(const Vector &vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) * *(vect.data + i));
}
return result;
}
int Vector:: size()
{
return num;
}
double Vector::operator[](int num)
{
return *(data + num);
}
ostream &operator <<(ostream &output, Vector &vect)
{
output << "[";
for (int i = 0; i < vect.size(); ++i)
{
output << vect[i];
if (i < vect.size() - 1)
output << ",";
}
output << "]\n";
return output;
}
istream &operator >>(istream &input, Vector &vect)
{
double element;
input >> element;
vect.insert(element);
return input;
}
int main()
{
Vector vec;
for (int i = 0; i < 10; ++i)
{
vec.insert(i);
}
return 0;
}
Look closely at your insert function. Specifically at how you are re-sizing the array.

Operator overloading unhandled exception

I am having some trouble overloading the + operator. I get a runtime error. Unhandled exception followed by a memory address.
Below is what I have coded:
#include <iostream>
#include <iomanip>
using namespace std;
class myVector{
int vsize, maxsize;
int* array;
void alloc_new();
friend ostream& operator<< (ostream &out, myVector&);
friend istream& operator>> (istream &in, myVector&);
public:
myVector();
myVector(int);
myVector(const myVector&); //copy constructor
~myVector();
void push_back(int);
int size();
int operator[](int);
myVector operator+(myVector&);
int at(int i);
};
myVector::myVector()
{
maxsize = 20;
array = new int[maxsize];
vsize = 0;
}
myVector::myVector(int i)
{
maxsize = i;
array = new int[maxsize];
vsize = 0;
}
myVector::myVector(const myVector& v){}
myVector::~myVector()
{
delete[] array;
}
void myVector::push_back(int i)
{
if (vsize + 1 > maxsize)
alloc_new();
array[vsize] = i;
vsize++;
}
int myVector::operator[](int i)
{
return array[i];
}
int myVector::at(int i)
{
if (i < vsize)
return array[i];
throw 10;
}
void myVector::alloc_new()
{
maxsize = vsize * 2;
int* tmp = new int[maxsize];
for (int i = 0; i < vsize; i++)
tmp[i] = array[i];
delete[] array;
array = tmp;
}
int myVector::size()
{
return vsize;
}
myVector myVector::operator+(myVector& a)
{
myVector result;
for (int i = 0; i < a.size(); i++)
result.array[i] = this->array[i] + a.array[i];
return result;
}
ostream& operator<< (ostream &out, myVector& a)
{
for (int i = 0; i < a.size(); i++)
out << a[i] << " ";
return out;
}
istream& operator>> (istream &in, myVector& a)
{
int tmp, lol;
cin >> tmp;
for (int i = 0; i < tmp; i++)
{
cin >> lol;
a.push_back(lol);
}
return in;
}
int main()
{
myVector vec;
myVector vec2;
myVector c;
int width = 15;
cout << "Input vector a\n";
cin >> vec; // In: 3 1 2 3
cout << "Input vector b\n";
cin >> vec2; // In: 3 4 5 6
cout << setw(width) << "Vector a: " << vec << endl;
cout << setw(width) << "Vector b: " << vec2 << endl;
cout << setw(width) << "c = a + b: " << c << endl;
c = vec + vec2;
system("PAUSE");
return 0;
}
How would I go about writing a copy constructor for a dynamic array? This is what I have right now:
myVector::myVector(const myVector &initial)
{
int* tmp = new int[3];
for (int i = 0; i < 3; i++)
tmp[i] = initial.array[i];
delete[] array;
array = tmp;
}
When you're assigning the results in your operator+, you've done nothing to reserve space in the results vector.
(You should slather your class in runtime checks (assert or similar) to sanity-check all the inputs to every method. That would show you that your result indexer passed in an index which didn't exist in the vector.)

operator overload for dynamic array giving strange error

I'm getting an error regarding "disgarded qualifiers" when I use this. The Entier class is posted below.
cout << d // where d is of type dynamic_array.
The global overloaded function:
template <class T> std::ostream& operator<<(std::ostream& stream, dynamic_array<T> const& data)
{
data.print_array(stream);
return stream;
}
A public member of dynamic_array
void print_array(std::ostream &os = cout)
{
for (int i = 0; i < size; i++) os << array[i] << endl;
}
Entire Class dynamic array:
/*
Needs a reszie function added
Merge sort is better for sequential, stable(equal elements not re-arranged, or
*/
#include "c_arclib.cpp"
using namespace std;
template <class T> class dynamic_array
{
private:
T* array;
T* scratch;
void merge_recurse(int left, int right)
{
if(right == left + 1)
{
return;
}
else
{
int i = 0;
int length = right - left;
int midpoint_distance = length/2;
int l = left, r = left + midpoint_distance;
merge_recurse(left, left + midpoint_distance);
merge_recurse(left + midpoint_distance, right);
for(i = 0; i < length; i++)
{
if((l < (left + midpoint_distance)) && (r == right || array[l] > array[r]))
{
scratch[i] = array[l];
l++;
}
else
{
scratch[i] = array[r];
r++;
}
}
for(i = left; i < right; i++)
{
array[i] = scratch[i - left];
}
}
}
void quick_recurse(int left, int right)
{
int l = left, r = right, tmp;
int pivot = array[(left + right) / 2];
while (l <= r)
{
while (array[l] < pivot)l++;
while (array[r] > pivot)r--;
if (l <= r)
{
tmp = array[l];
array[l] = array[r];
array[r] = tmp;
l++;
r--;
}
}
if (left < r)quick_recurse(left, r);
if (l < right)quick_recurse(l, right);
}
public:
int size;
dynamic_array(int sizein)
{
size=sizein;
array = new T[size]();
}
void print_array(std::ostream &os = cout)
{
for (int i = 0; i < size; i++) os << array[i] << endl;
}
void print_array()
{
for (int i = 0; i < size; i++) cout << array[i] << endl;
}
int merge_sort()
{
scratch = new T[size]();
if(scratch != NULL)
{
merge_recurse(0, size);
return 1;
}
else
{
return 0;
}
}
void quick_sort()
{
quick_recurse(0,size);
}
void rand_to_array()
{
srand(time(NULL));
int* k;
for (k = array; k != array + size; ++k)
{
*k=rand();
}
}
void order_to_array()
{
int* k;
int i = 0;
for (k = array; k != array + size; ++k)
{
*k=i;
++i;
}
}
void rorder_to_array()
{
int* k;
int i = size;
for (k = array; k != array + size; ++k)
{
*k=i;
--i;
}
}
};
template <class T> std::ostream& operator<<(std::ostream& stream, dynamic_array<T> const& data)
{
data.print_array(stream);
return stream;
}
int main()
{
dynamic_array<int> d1(1000000);
d1.order_to_array();
clock_t time_start=clock();
d1.merge_sort();
clock_t time_end=clock();
double result = (double)(time_end - time_start) / CLOCKS_PER_SEC;
cout << result;
cout << d1;
}
The problem is in following lines:
template <class T>
std::ostream& operator<<(std::ostream& stream, dynamic_array<T> const& data)
^^^^^^
and
void print_array(std::ostream &os = cout) /* const */
^^^^^ missing
Since you are passing data as const& to operator <<, you have to maintain its const qualification. i.e. data cannot call any non-const member of class dynamic_array. You can solve this problem in 2 ways:
pass data as simple dynamic_array<T>& to operator <<
make print_array a const method (uncomment above)
"Discards const qualifiers", presumably...
Replace:
void print_array(std::ostream &os = cout)
{
for (int i = 0; i < size; i++) os << array[i] << endl;
}
void print_array()
{
for (int i = 0; i < size; i++) cout << array[i] << endl;
}
...with...
void print_array(std::ostream &os = cout) const
{
for (int i = 0; i < size; i++) os << array[i] << endl;
}
...or, better still ...
void print_array(std::ostream &os = cout) const
{
std::copy(array, array + size, std::ostream_iterator<T>(os, "\n"));
}
This member function can be declared const since it doesn't modify any attributes of the class. See the FAQ on Const-Correctness.
Your second print_array() method is redundant since the first takes a default argument of std::cout.