Why two outcomes are different in the case of operator overloading? - c++

I have this code of overloaded operator for vectors class, which is a class of vector of dimension 3:
class Vectors
{
//private:
// double* vector;
public:
double* vector;
Vectors(double*);
Vectors();
Vectors(const Vectors&);
~Vectors();
void print_vector();
};
Class Methods:
Constructors:
Vectors::Vectors(double* value)
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = value[i];
}
}
Vectors::Vectors()
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = 0.0;
}
}
Copy Constructors:
Vectors::Vectors(const Vectors& copy)
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = copy.vector[i];
}
}
Destructor:
Vectors::~Vectors()
{
//cout << "desctructor called \n";
delete[] vector;
}
void Vectors::print_vector(){
for (int i=0; i<3 ;i++){
cout << this->vector[i];
cout << '\t';
}
cout << endl;
}
Overloaded Operator:
Vectors operator+(const Vectors& obj1,const Vectors& obj2)
{
Vectors *res = new Vectors;
for (int i = 0; i < 3; i++){
//cout << obj1.vector[i] << '\t' << obj2.vector[i] << '\t' << obj1.vector[i] + obj2.vector[i] << endl;
res->vector[i] = obj1.vector[i] + obj2.vector[i];
//cout << res->vector[i] << endl;
}
//res->print_vector();
return *res;
}
int main()
{
double a[3] = {3.5,4.10,5.30};
double b[3] = {7.0,8.0,9.0};
Vectors* A = new Vectors(a);
Vectors* B = new Vectors(b);
Vectors* C = new Vectors();
*C = *A+*B; // This does not work
(*A+*B).print_vector(); // This works
C->print_vector();
Vectors D = *A+*B; // This works
D.print_vector();
}
When creating a pointer to an object Vectors, I get different results when compared to creating direct objects.
Output is:
1st Output:
0 4.68558e-310 14.3
2nd Output:
10.5 12.1 14.3
3rd Output:
10.5 12.1 14.3

This version works, but I have still got memory leak using valgrind. Can somebody point out where?
#include <iostream>
using namespace std;
class Vectors
{
//private:
// double* vector;
public:
double* vector;
Vectors(double*);
Vectors();
Vectors(const Vectors&);
~Vectors();
void print_vector();
Vectors operator=(const Vectors&);
};
Vectors::Vectors(double* value)
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = value[i];
}
}
Vectors::Vectors()
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = 0.0;
}
}
Vectors::Vectors(const Vectors& copy)
{
this->vector = new double[3];
for (auto i = 0; i < 3; i++)
{
this->vector[i] = copy.vector[i];
}
//this->vector = (copy.vector);
}
Vectors::~Vectors()
{
//cout << "desctructor called \n";
delete[] vector;
}
void Vectors::print_vector(){
for (int i=0; i<3 ;i++){
cout << this->vector[i];
cout << '\t';
}
cout << endl;
}
Vectors Vectors::operator=(const Vectors& obj1)
{
this->vector = new double[3];
if (this != &obj1)
{
for (int i = 0; i < 3; i++) {
this->vector[i] = obj1.vector[i];
}
}
return *this;
}
Vectors operator+(const Vectors& obj1,const Vectors& obj2)
{
Vectors res;
for (int i = 0; i < 3; i++){
res.vector[i] = obj1.vector[i] + obj2.vector[i];
}
return res;
}
int main()
{
double a[3] = {3.5,4.10,5.30};
double b[3] = {7.0,8.0,9.0};
Vectors* A = new Vectors(a);
Vectors* B = new Vectors(b);
Vectors* C = new Vectors();
*C = *A+*B;
C->print_vector();
//(*A+*B).print_vector();
//cout << C->vector[1]<<endl;
//double a[3] = {3.5,4.10,5.30};
//double b[3] = {7.0,8.0,9.0};
//Vectors A(a), B(b);
Vectors D = *A+*B;
//Vectors C = A-B;
//Vectors C = A*B;
//Vectors C = 5*A;
//Vectors C = 5.5*A;
//Vectors C = A/B;
//Vectors C = 5/A;
//Vectors C = 5.5/A;
D.print_vector();
delete[] A;
delete[] B;
delete[] C;
}

Related

can't figure out where the heap overwriting is

#include<iostream>
using namespace std;
class Text{
public:
~Text(){
delete data;
}
char* data{};
int mSize{};
void fill(char* stringInput) {
mSize = strlen(stringInput);
data = new char [mSize];
for (int i = 0; i < mSize; i++){
data[i] = stringInput[i];
}
}
};
class myString{
public:
explicit myString(int size){ // constructor
strAmount = size;
strings = new Text [size];
}
~myString(){ // destructor
delete[] strings;
}
void addString(char* input){
strings[filledAmount].fill(input);
filledAmount++;
}
void delString(int pos){
for ( int i = pos; i < filledAmount; i++){
swap(strings[i], strings[i+1]);
}
strings[filledAmount].data = nullptr;
strings[filledAmount].mSize = 0;
filledAmount--;
}
void eraseEverything(){
for ( int i = 0; i < filledAmount; i++){
strings[i].data = {};
strings[i].mSize = 0;
}
filledAmount = 0;
}
int maxString() const {
int index{};
for ( int i = 0 ; i < filledAmount; i++){
if (strings[i].mSize > strings[index].mSize){
index = i;
}
}
return index;
}
int charAmount(){
int counter{};
for(int i = 0 ; i < filledAmount; i++){
counter+=strings[i].mSize;
}
return counter;
}
double digitPercentage(){
int digitsAmount{};
for(int i = 0; i < filledAmount; i++){
for ( int j = 0; j < strings[i].mSize; j++){
if (isdigit(strings[i].data[j])){
digitsAmount++;
}
}
}
double digitPercent = (digitsAmount/(double)charAmount())*100;
return digitPercent;
}
int filledAmount{};
int strAmount{};
Text* strings;
};
void render_text(myString& obj) {
for (int k = 0; k < obj.filledAmount; k++) {
for (int i = 0; i < obj.strings[k].mSize; i++)
cout << obj.strings[k].data[i];
cout << endl;
}
cout << endl;
}
int main(){
myString a(5);
a.addString((char *) "zxc 1v1 forever shadow fiend");
a.addString((char *) "This is a string");
a.addString((char *) "12345");
a.addString((char *) "Hello");
a.addString((char *) "A1oha Dance");
render_text(a);
a.delString(1);
render_text(a);
int maxInd = a.maxString();
cout << "Max string :\n";
for (int i = 0; i < a.strings[maxInd].mSize; i++) {
cout << a.strings[maxInd].data[i];
}
cout << "\n\n";
}
Please help me find the crash point. I suppose it crashes in the destructor pole, but I still can't figure it out.
This is something like a self-written string class, the problem is that I can't find the place where the problems start.
I also have a thought that the destructor tries to delete too much memory from the heap so the compiler prevents it from doing that. Can I somehow change the size of the strings array?
I have fixed all your memory errors, with the help of address sanitizers
The main change here is:
Add copy constructors and copy assignment operators
Manually delete the last element in the function delString
Though that the code now works, it's not a true modern c++ style code. I highly recommend that your using std::string to replace your Text class. Use std::vector to replace the dynamic array. Then you will stay away from the pain of memory errors. The delString should be replaced with vector::erase,which is much neat than your hand write algorithm.
https://en.cppreference.com/w/cpp/string/basic_string
https://en.cppreference.com/w/cpp/container/vector
I strongly recommend rewriting the code with std::string and std::vector
#include <cstring>
#include <iostream>
using namespace std;
class Text {
public:
~Text() { delete[] data; }
char* data{};
int mSize{};
Text() = default;
Text(const Text& oth) {
mSize = oth.mSize;
data = new char[mSize];
std::copy(oth.data, oth.data + oth.mSize, data);
}
Text& operator=(const Text& oth) {
delete[] data;
mSize = oth.mSize;
data = new char[mSize];
std::copy(oth.data, oth.data + oth.mSize, data);
return *this;
}
void fill(char* stringInput) {
mSize = strlen(stringInput) + 1;
data = new char[mSize];
for (int i = 0; i < mSize; i++) {
data[i] = stringInput[i];
}
}
};
class myString {
public:
explicit myString(int size) { // constructor
strAmount = size;
strings = new Text[size];
}
myString(const myString& oth) {
strAmount = oth.strAmount;
strings = new Text[oth.strAmount];
for (size_t i = 0; i < strAmount; ++i) {
strings[i] = oth.strings[i];
}
}
myString& operator=(const myString& oth) {
delete[] strings;
strAmount = oth.strAmount;
strings = new Text[oth.strAmount];
for (size_t i = 0; i < strAmount; ++i) {
strings[i] = oth.strings[i];
}
return *this;
}
~myString() { // destructor
delete[] strings;
}
void addString(char* input) {
strings[filledAmount].fill(input);
filledAmount++;
}
void delString(int pos) {
for (int i = pos; i < filledAmount; i++) {
swap(strings[i], strings[i + 1]);
}
delete[] strings[filledAmount].data;
strings[filledAmount].data = nullptr;
strings[filledAmount].mSize = 0;
filledAmount--;
}
void eraseEverything() {
for (int i = 0; i < filledAmount; i++) {
strings[i].data = {};
strings[i].mSize = 0;
}
filledAmount = 0;
}
int maxString() const {
int index{};
for (int i = 0; i < filledAmount; i++) {
if (strings[i].mSize > strings[index].mSize) {
index = i;
}
}
return index;
}
int charAmount() {
int counter{};
for (int i = 0; i < filledAmount; i++) {
counter += strings[i].mSize;
}
return counter;
}
double digitPercentage() {
int digitsAmount{};
for (int i = 0; i < filledAmount; i++) {
for (int j = 0; j < strings[i].mSize; j++) {
if (isdigit(strings[i].data[j])) {
digitsAmount++;
}
}
}
double digitPercent = (digitsAmount / (double)charAmount()) * 100;
return digitPercent;
}
int filledAmount{};
int strAmount{};
Text* strings = nullptr;
};
void render_text(myString& obj) {
for (int k = 0; k < obj.filledAmount; k++) {
for (int i = 0; i < obj.strings[k].mSize; i++)
cout << obj.strings[k].data[i];
cout << endl;
}
cout << endl;
}
int main() {
myString a(6);
a.addString((char*)"zxc 1v1 forever shadow fiend");
a.addString((char*)"This is a string");
a.addString((char*)"12345");
a.addString((char*)"Hello");
a.addString((char*)"A1oha Dance");
render_text(a);
a.delString(1);
render_text(a);
int maxInd = a.maxString();
cout << "Max string :\n";
for (int i = 0; i < a.strings[maxInd].mSize; i++) {
cout << a.strings[maxInd].data[i];
}
cout << "\n\n";
return 0;
}

Copying data in a simple vector class

I'm trying write my own vector class:
template <typename T>
class Vector {
public:
Vector(int default_size = 2) :
size(0), data_member(new T[default_size]), capacity(default_size) {};
Vector(const Vector& obj)
{
data_member = new T[obj.size];
data_member = obj.data_member;
size = obj.size;
capacity = obj.capacity;
}
void push_back(T& elem)
{
if (size == capacity)
resize(2 * size);
data_member[size] = elem;
size++;
}
void push_front(T& data)
{
if (size + 1 == capacity)
resize(2 * size);
for (int i = size - 1; i >= 0; i--)
{
data_member[i + 1] = data_member[i];
}
data_member[0] = data;
size++;
}
void pop_back()
{
--size;
}
void resize(int size_)
{
if (size_ > capacity)
{
T* temp = new T[size_];
memcpy(temp, data_member, size * sizeof(T));
delete[] data_member;
data_member = new T[size_];
data_member = temp;
//delete[] temp;
capacity = size_;
}
}
int get_size() { return size; }
T* getarr() { return data_member; }
private:
T* data_member;
int size;
int capacity;
};
and here is a main for testing my class
int main()
{
Vector<int> myint;
int a = 5, b = 8, c = 9;
myint.push_back(a);
myint.push_back(b);
myint.push_back(c);
Vector<int> you = myint;
int* arr1 = you.getarr();
for (int i = 0; i < you.get_size(); i++)
{
cout << *arr1 << endl;
arr1++;
}
cout << endl << endl;
int h[3] = { 1,2,3 };
int* hp = h;
int g[3] = { 4,5,6 };
int* gp = g;
int f[3] = { 4,5,6 };
int* fp = f;
Vector<int*> myarrint;
myarrint.push_back(hp);
myarrint.push_back(gp);
myarrint.push_back(fp);
int** arr = myarrint.getarr();
for (int i = 0; i < myarrint.get_size(); i++)
{
for (int j = 0; j < 3; j++)
{
cout << **arr << endl;
(*arr)++;
}
arr++;
}
cout << endl << endl;
Vector<string> mystr;
string s1 = "I";
string s2 = "went";
string s3 = "shopping";
mystr.push_back(s1);
mystr.push_back(s2);
mystr.push_back(s3);
string* str1 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str1 << endl;
str1++;
}
cout << endl << endl;
string i = "wow";
mystr.push_front(i);
string* str2 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str2 << endl;
str2++;
}
cout << endl << endl;
return 0;
}
I'm new in c++ and I'm really confused, I think in my push_back function, I'm just making my objects point to temp and I'm not copying temp in them , so if I want to delete temp in the end of my push_back function my data_members will be lost. So what is the right way to do so?
second if I want to make a dynamic array of strings my program will crash sometimes, and I think ,it's because of memcpy() in my resize function, still I don't know what should I do instead of it?

How do I write a moving Average to an array list class?

I'm trying to make an arraylist class where I make a moving Average function in my arraylist class while outputting the moving average of my arraylist class.
I've tried various research and examples online and I've officially hit a wall. Can someone please help me fix my problem. I really need to get this fixed as soon as possible. Code was provided by my professor.
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#include<iostream>
using namespace std;
class arrayList {
int size;
int capacity;
double * p;
void resize() {
capacity *= 2;
double * temp = new double[capacity];
for (int i = 0; i < size; i++) {
temp[i] = p[i];
}
delete[] p;
p = temp;
}
}
public:
arrayList(): size(0), capacity(1) {
p = new double[capacity];
}
arrayList(int cap): size(0), capacity(cap) {
p = new double[capacity];
}
//copy constructor
arrayList(const arrayList & copy) {
size = copy.size;
capacity = copy.capacity;
p = new double[capacity];
for (int i = 0; i < size; ++i)
p[i] = copy.p[i];
}
//move constructor
arrayList(arrayList && move) {
size = move.size;
capacity = move.capacity;
p = move.p;
move.size = 0;
move.capacity = 0;
move.p = nullptr;
}
//copy assignment operator
arrayList & operator = (const arrayList & copyA) {
if (this != & copyA) {
size = copyA.size;
capacity = copyA.capacity;
p = new double[capacity];
for (int i = 0; i < copyA.size; ++i)
p[i] = copyA.p[i];
delete[] p;
}
return *this;
}
// move assignment operator
arrayList & operator = (arrayList moveA) {
if (this != & moveA) {
size = moveA.size;
capacity = moveA.capacity;
delete[] p;
p = moveA.p;
moveA.p = nullptr;
}
return *this;
}
//destructor
~arrayList() {
delete[] p;
}
void insert(int index, int value) {
if (index >= capacity) {
cout << "OUT OF BOUNDS!";
}
if (index < size && index >= 0) {
for (int i = size; i > index; --i) {
p[i] = p[i - 1];
}
p[index] = value;
size++;
} else {
p[index] = value;
size++;
}
}
void append(int val) {
if (size == capacity)
resize();
p[size] = val;
size++;
}
void movingAvg(const arrayList & val, int kernel) {
for (int i = 0; i < val.size; ++i) {
kernel = val.p[i];
val.p[i] = kernel[val.size - 1 - i];
kernel[size - 1 - i] = kernel;
cout << "average of the array is: " << val.p;
}
friend ostream & operator << (ostream & os, arrayList & val) {
for (int i = 0; i < val.size; ++i)
os << val.p[i] << " ";
os << endl << endl;
return os;
}
};
// main.cpp
int main() {
arrayList a;
a.append(45);
cout << a;
a.append(14);
cout << a;
a.insert(2, 76);
cout << a;
//CRASHES AT THIS POINT!
a.insert(3, 45);
cout << a;
a.insert(5, 23);
cout << a;
return 0;
}
OUTPUT:
45
45 14
45 14 76 0
You are deleting p more than once in your resize function. That's likely the source of your crash.
Instead of this:
void resize(){
capacity *= 2; //THIS IS WHAT'S CRASHING THE CODE
double *temp = new double[capacity];
for(int i = 0; i < size; i++){
temp[i] = p[i];
delete []p;
p = temp;
temp = nullptr;
}
}
Implement this:
void resize() {
capacity *= 2;
double *temp = new double[capacity];
for (int i = 0; i < size; i++) {
temp[i] = p[i];
}
delete [] p;
p = temp;
}
And if you want to be more efficient with the copy loop:
void resize() {
capacity *= 2;
double *temp = new double[capacity];
memcpy(temp, p, sizeof(double)*size);
delete [] p;
p = temp;
}

How to properly implement a copy constructor for a dynamic Matrix?

I have a Matrix (Matriz) class implemented as following:
Header:
#ifndef MATRIZ_H
#define MATRIZ_H
class Matriz
{
public:
Matriz(unsigned int nL, unsigned int nC);
~Matriz();
Matriz& operator+=(const Matriz &ptr);
const Matriz operator+(const Matriz &ptr) const;
Matriz* subtracaoMatriz(Matriz *m);
Matriz* multiplicacaoMatriz(Matriz *m);
void inserirMatriz();
void imprimirMatriz();
int verificaOperacao(const Matriz& ptr);
Matriz& operator-=(const Matriz &ptr);
const Matriz operator-(const Matriz &ptr) const;
const Matriz operator*(const Matriz &ptr) const;
protected:
private:
unsigned int nLinhas;
unsigned int nColunas;
int** matrix;
int verificaOperacao(Matriz *m); //0 -> cannot make the operation; 1 -> OK for product; 2 -> OK for sum;
};
#endif // MATRIZ_H
Implementation:
#include "Matriz.h"
#include <iostream>
using namespace std;
Matriz::Matriz(unsigned int nL, unsigned int nC)
{
this->nLinhas = nL;
this->nColunas = nC;
this->matrix = new int*[nLinhas];
for (unsigned int i = 0; i < nLinhas; ++i)
this->matrix[i] = new int[nColunas];
for(unsigned int i = 0; i < nLinhas; i++)
for(unsigned int j = 0; j < nColunas; j++)
this->matrix[i][j] = 0;
}
Matriz::~Matriz()
{
//dtor
}
int Matriz::verificaOperacao(Matriz *m)
{
if((this->nLinhas == m->nLinhas) && (this->nColunas == m->nColunas))
return 2;
else if(this->nColunas == m->nLinhas)
return 1;
else
return 0;
}
int Matriz::verificaOperacao(const Matriz& ptr)
{
if((this->nLinhas == ptr.nLinhas) && (this->nColunas == ptr.nColunas))
return 2;
else if(this->nColunas == ptr.nLinhas)
return 1;
else
return 0;
}
Matriz& Matriz::operator+=(const Matriz &ptr) {
if(this->verificaOperacao(ptr) == 2)
{
for(unsigned int i = 0; i < this->nLinhas; i++)
for(unsigned int j = 0; j < this->nColunas; j++)
this->matrix[i][j] = this->matrix[i][j] + ptr.matrix[i][j];
return *this;
}
else
return *this;
}
const Matriz Matriz::operator+(const Matriz &ptr) const {
Matriz resultado = *this;
resultado += ptr;
return resultado;
}
Matriz& Matriz::operator-=(const Matriz &ptr) {
if(this->verificaOperacao(ptr) == 2)
{
for(unsigned int i = 0; i < this->nLinhas; i++)
for(unsigned int j = 0; j < this->nColunas; j++)
this->matrix[i][j] = this->matrix[i][j] - ptr.matrix[i][j];
return *this;
}
else
return *this;
}
const Matriz Matriz::operator-(const Matriz &ptr) const {
Matriz resultado = *this;
resultado -= ptr;
return resultado;
}
const Matriz Matriz::operator*(const Matriz &ptr) const {
Matriz *resultado = new Matriz(this->nLinhas, ptr.nColunas);
for(unsigned i = 0; i < this->nLinhas; i++)
{
for(unsigned j = 0; j < ptr.nColunas; j++)
for(unsigned int aux = 0; aux < ptr.nColunas; aux++)
resultado->matrix[i][j] += this->matrix[i][aux] * ptr.matrix[aux][j];
}
return *resultado;
}
void Matriz::inserirMatriz()
{
for(unsigned int i = 0; i < this->nLinhas; i++)
for(unsigned int j = 0; j < this->nColunas; j++)
cin >> this->matrix[i][j];
}
void Matriz::imprimirMatriz()
{
for(unsigned int i = 0; i < this->nLinhas; i++) {
for(unsigned int j = 0; j < this->nColunas; j++)
cout << this->matrix[i][j] << "\t";
cout << endl;
}
}
Main:
#include <iostream>
#include "Matriz.h"
using namespace std;
int main()
{
Matriz *m1 = new Matriz(2, 2);
Matriz *m2 = new Matriz(2, 2);
m1->inserirMatriz();
m2->inserirMatriz();
cout << "Matrix 1:" << endl;
m1->imprimirMatriz();
cout << "Matrix 2:" << endl;
m2->imprimirMatriz();
Matriz m3 = *m1 + *m2;
cout << "The sum is: " << endl;
m3.imprimirMatriz();
cout << "The subtraction is: " << endl;
Matriz m4 = *m1 - *m2;
m4.imprimirMatriz();
cout << "The product is: " << endl;
Matriz m5 = *m1 * *m2;
m5.imprimirMatriz();
///HERE LIES THE PROBLEM
m2 = m1;
cout << "m2 = m1" << endl;
cout << "m2:" << endl;
m2->imprimirMatriz();
cout << "*m1 += *m2" << endl;
cout << "m2:" << endl;
*m1 += *m2;
m2->imprimirMatriz();
delete m1;
delete m2;
return 0;
}
I believe that the issue is caused by the default copy constructor, however I tried without success to implement one.
There are two ways to implement a copy constructor:
Method 1
Use a std::vector instead of dynamic memory, this approach eliminates the need for a custom copy constructor and removes the risk of memory leaks, see here. I'm not going to rewrite your code but do some simple stuff to illustrate the point:
// Header file
#include <vector>
class Matriz
{
...
private:
std::vector<std::vector<int>> matrix;
}
// CPP file
Matriz::Matriz(unsigned int nL, unsigned int nC)
{
matrix.resize(nL, std::vector<int>(nC, 0));
// You can now access items with matrix[x][y].
}
This method with vectors works because when you want to copy your Matriz class the copy constructors for the vector will automatically be called. It's all done for you.
Method 2
If you still want to use dynamic memory then you need to implement a deep copy constructor:
//Header file.
class Matriz
{
...
Matriz(const Matriz& m);
}
// CPP file
Matriz::~Matriz() { delete[] matrix; } // DO NOT FORGET THIS!!!
Matriz::Matriz(const Matriz& m)
{
delete[] matrix;
// Create the dynamic memory.
int** matrix = new int*[m.nLinhas];
for(int i = 0; i < m.nLinhas; ++i)
matrix[i] = new int[nColunas];
nLinhas = m.nLinhas;
nColunas = m.Colunas;
// Copy over the data.
for(int l = 0; l < nLinhas; l++)
{
for(int c = 0; c < nColunas; c++)
{
matrix[l][c] = m.matrix[l][c];
}
}
}
You can follow the same concepts for the assignment operator operator=. I would suggest using the vector if you can, this will eliminate any possible leak issues and given what you are doing there won't be any speed loss issues.

C++ HEAP error when delete [] is called

I keep getting the error in VS 2100 "CRT detected that the application wrote to memory before start of heap buffer"
Can anyone help? My int Main is all the way on the bottom. The error occur when the delete [] command is run on the operator= function
#include "intset.h"
const int MAXINITIALSIZE = 5;
int IntSet::numOfArray = 0;
IntSet::IntSet(int a, int b, int c, int d, int e)
{
numOfArray++;
int tempArray[] = {a, b, c, d, e};
size = determineHighest(tempArray) + 1; //determines largest int
cout << "size is " << size << endl;
arrayPtr = new bool[size]; //creates array of bool
for (int i = 0; i < size; i++) //fill bool array
{
arrayPtr[i]= false; //arrayptr is a bool pointer created in the header
}
for (int i = 0; i < MAXINITIALSIZE; i++)
{
arrayPtr[tempArray[i]]= true;
}
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
}
IntSet::IntSet(const IntSet &intsetObject)
{
numOfArray++;
size = intsetObject.size;
arrayPtr = new bool[size];
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
IntSet::~IntSet()
{
--numOfArray;
delete [] arrayPtr;
arrayPtr = NULL;
}
int IntSet::determineHighest(int tempArray[])
{
int temp = tempArray[0];
for (int i = 1; i < MAXINITIALSIZE; i++)
{
if (tempArray[i] > temp)
temp = tempArray[i];
else
continue;
}
return temp;
}
IntSet& IntSet::operator=(const IntSet &intsetObject) //ask about IntSet&
{
cout << "inside operator=" << endl;
if (&intsetObject != this)
{
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
delete [] arrayPtr; //HEAP ERROR HERE!
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
size = intsetObject.size
arrayPtr = new bool[size]();
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
return *this;
}
ostream& operator<<(ostream &output, const IntSet &intsetObject)
{
output << "{ ";
for (int i = 0; i < intsetObject.size; i++)
{
if (intsetObject.arrayPtr[i] == true)
{
output << i << " ";
}
else
continue;
}
output << "}";
return output;
}
//main
#include "intset.h"
int main() {
IntSet object2(9);
IntSet object4(3,6);
object4 = object2;
return 0;
}
This can only happen if arrayPtr is accessed with a negative index. I suspect your defaults for a,b,c,d,e are -1 in the declaration for IntSet::IntSet, so it is writing to arrayPtr[-1] in the set-true loop. Check for tempArray[i] >= 0 there.
Also, you can't print the array after you have deleted it, so you should remove those lines after the delete, although they should be "harmless" in that only garbage will be printed, but who knows - the OS could release the page containing the array and it could segfault your program.
Finally, you should not test if (intsetObject.arrayPtr[i]) in the copy & = operators. Otherwise all "false" elements in the source array become uninitialized in the destination array (new bool[size] does not initialize the array to all false).