C++ EXC_BAD_ACCESS of Tree Root Node - c++

I'm building an Octree for computer graphics. Trying to build the tree with following code:
void Accel::build() {
Octree *m_octree = new Octree(depth);
std::vector<uint32_t> indices(triangleCount);
for (uint32_t i = 0; i < triangleCount; ++i) {
indices[i] = i;
}
m_octree->root = m_octree->octreeBuild(m_bbox, indices, m_mesh);
}
The tree and tree node class are like the following:
Octree.h
class Octree {
public:
uint32_t totalNodes = 0;
uint32_t maxDepth = 0;
uint32_t totalDepth = 0;
std::vector<OctreeNode *> octreeVector;
OctreeNode *root;
Octree();
Octree(uint32_t d);
~Octree();
OctreeNode *octreeBuild(BoundingBox3f boundingBox, std::vector<uint32_t> indices, Mesh* mesh);
};
Octree.cpp
Octree::Octree(){}
Octree::Octree(uint32_t d): maxDepth(d) {}
Octree::~Octree(){
}
OctreeNode *Octree::octreeBuild(BoundingBox3f boundingBox, std::vector<uint32_t> indices, Mesh* mesh) {
if (indices.empty()) {
OctreeNode *node = nullptr;
octreeVector.push_back(node);
return node;
}
if (indices.size() <= 10 || totalDepth == maxDepth) {
OctreeNode *node = new OctreeNode(indices, boundingBox, true);
octreeVector.push_back(node);
totalNodes += 1;
return node;
}
if (totalDepth < maxDepth){
std::vector<uint32_t> nodeArray[8]; // Eight vector to store child node indices
BoundingBox3f boxArray[8] = {
boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox
}; // Eight bounding box, one for each child node
for (uint32_t i = 0; i < 8; ++i) { // Seperate bounding box
Point3f corner = boundingBox.getCorner(i);
Point3f center = boundingBox.getCenter();
Point3f minPoint = Point3f(std::min(corner.x(), center.x()), std::min(corner.y(), center.y()), std::min(corner.z(), center.z()));
Point3f maxPoint = Point3f(std::max(corner.x(), center.x()), std::max(corner.y(), center.y()), std::max(corner.z(), center.z()));
boxArray[i] = BoundingBox3f(minPoint, maxPoint);
}
for (uint32_t i = 0; i < static_cast<uint32_t>(indices.size()); i++) { // Check overlapping, store indices to cooresponding vector
BoundingBox3f triangleBox = mesh->getBoundingBox(i);
for (uint32_t j = 0; j < 8; ++j) {
if (boxArray[j].overlaps(triangleBox) && boxArray[j].contains(triangleBox.getCenter())) {
nodeArray[j].push_back(i);
break;
}
}
}
OctreeNode *node = new OctreeNode(indices, boundingBox, false); // Build the new node with children
octreeVector.push_back(node);
if (octreeVector.size() == 1) {
root = node;
}
totalDepth += 1;
for (uint32_t i = 0; i < 8; ++i) {
node->child[i] = octreeBuild(boxArray[i], nodeArray[i], mesh);
totalNodes += 1;
}
return node;
}
return nullptr;
};
I manage to build the program and the Octree::build went through without error messages. But after trying to search form the tree root, I got the EXC_BAD_ACCESS error. It seems like the root of my octree is lost. I'm new to C++, not sure if that's because the algorithms or the way I program with C++ was wrong. Thanks for any advice!

Related

Im trying to make an astar algorithm for a school thing

Here is my code i've been working on. I've scraped off all the errors from the code. But i cant get the code to run correctly and the application either explodes or doesn't atleast visualise the astar.
#include <SFML/Graphics.hpp>
#include <queue>
#include <unordered_map>
#include <cmath>
#include <vector>
const int WIDTH = 10;
const int HEIGHT = 10;
struct Node
{
int x;
int y;
mutable float gScore;
mutable float fScore;
mutable const Node* parent;
Node(int _x, int _y) : x(_x), y(_y), gScore(0), fScore(0), parent(nullptr) {}
bool operator==(const Node& other) const
{
return x == other.x && y == other.y;
}
};
// Hash function for nodes, needed for storing them in an unordered_map
struct NodeHash
{
std::size_t operator()(const Node& node) const
{
return std::hash<int>()(node.x) ^ std::hash<int>()(node.y);
}
};
// Overload the ">" operator for nodes, needed for using them in a priority queue
struct NodeGreater
{
bool operator()(const Node& left, const Node& right) const
{
return left.fScore > right.fScore;
}
};
// Represents a 2D grid
class Grid
{
public:
Grid()
{
// Initialize the grid with all nodes as walkable
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < HEIGHT; y++)
{
nodes[x][y] = true;
}
}
}
// Set the walkability of a node
void setNode(int x, int y, bool walkable)
{
nodes[x][y] = walkable;
}
// Check if a node is walkable
bool isNodeWalkable(int x, int y)
{
return nodes[x][y];
}
private:
bool nodes[WIDTH][HEIGHT];
};
// Calculate the Euclidean distance between two nodes
float euclideanDistance(Node a, Node b)
{
int xDist = b.x - a.x;
int yDist = b.y - a.y;
return std::sqrt(xDist * xDist + yDist * yDist);
}
// Estimate the cost of reaching the end node from a given node
float heuristicCostEstimate(Node start, Node end)
{
return euclideanDistance(start, end);
}
// Get the neighbors of a given node
std::vector<Node> getNeighbors(Grid grid, Node node)
{
std::vector<Node> neighbors;
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
// Skip the current node
if (x == 0 && y == 0)
{
continue;
}
int neighborX = node.x + x;
int neighborY = node.y + y;
// Make sure the neighbor is within the bounds of the grid
if (neighborX >= 0 && neighborX < WIDTH && neighborY >= 0 && neighborY < HEIGHT)
{
// Make sure the neighbor is walkable
if (grid.isNodeWalkable(neighborX, neighborY))
{
Node neighbor = { neighborX, neighborY };
neighbors.push_back(neighbor);
}
}
}
}
return neighbors;
}
// Reconstruct the path from the end node to the start node
std::vector<Node> reconstructPath(Node end)
{
std::vector<Node> path;
Node current = end;
while (current.parent != nullptr)
{
path.push_back(current);
current = *current.parent;
}
path.push_back(current);
std::reverse(path.begin(), path.end());
return path;
}
// Run the A* algorithm to find the shortest path from the start to the end node
std::vector<Node> aStar(Grid grid, Node start, Node end)
{
// Initialize the open and closed sets
std::priority_queue<Node, std::vector<Node>, NodeGreater> openSet;
std::unordered_map<Node, bool, NodeHash> closedSet;
// Add the start node to the open set
openSet.push(start);
// Set the starting node's gScore to 0 and fScore to the estimated cost to the end node
start.gScore = 0;
start.fScore = heuristicCostEstimate(start, end);
// Keep searching until the open set is empty
while (!openSet.empty())
{
// Get the node in the open set with the lowest fScore
Node current = openSet.top();
openSet.pop();
// If the current node is the end node, we have found the shortest path
if (current == end)
{
return reconstructPath(current);
}
// Add the current node to the closed set
closedSet[current] = true;
// Get the neighbors of the current node
std::vector<Node> neighbors = getNeighbors(grid, current);
// Iterate through the neighbors
for (const Node& neighbor : neighbors)
{
// Skip the neighbor if it is already in the closed set
if (closedSet.count(neighbor) > 0)
{
continue;
}
// Calculate the tentative gScore for the neighbor
float tentativeGScore = current.gScore + euclideanDistance(current, neighbor);
bool neighborIsBetter = false;
bool neighborInOpenSet = false;
// Check if the neighbor is already in the open set
std::priority_queue<Node, std::vector<Node>, NodeGreater> tempOpenSet = openSet;
while (!tempOpenSet.empty())
{
Node tempNeighbor = tempOpenSet.top();
tempOpenSet.pop();
if (tempNeighbor == neighbor)
{
neighborInOpenSet = true;
break;
}
}
// Update the neighbor's scores and parent if the tentative gScore is lower than
if (tentativeGScore < neighbor.gScore)
{
neighborIsBetter = true;
neighbor.gScore = tentativeGScore;
neighbor.fScore = tentativeGScore + heuristicCostEstimate(neighbor, end);
}
if (!neighborInOpenSet || neighborIsBetter)
{
// Update the neighbor's parent to the current node
neighbor.parent = &current;
// Add the neighbor to the open set if it is not already there
if (!neighborInOpenSet)
{
openSet.push(neighbor);
}
}
}
}
// If we reach here, it means that we have not found a path to the end node
return std::vector<Node>();
}
int main()
{
// Create the window and grid
sf::RenderWindow window(sf::VideoMode(500, 500), "A*");
Grid grid;
// Set some nodes as unwalkable
grid.setNode(3, 3, false);
grid.setNode(3, 4, false);
grid.setNode(3, 5, false);
grid.setNode(4, 3, false);
// Set the start and end nodes
Node start = { 1, 1 };
Node end = { 8, 8 };
// Run the A* algorithm and get the path
std::vector<Node> path = aStar(grid, start, end);
// Main loop
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
// Draw the grid
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < HEIGHT; y++)
{
sf::RectangleShape rect(sf::Vector2f(50, 50));
rect.setPosition(x * 50, y * 50);
if (grid.isNodeWalkable(x, y))
{
rect.setFillColor(sf::Color::White);
}
else
{
rect.setFillColor(sf::Color::Black);
}
window.draw(rect);
}
}
// Draw the path
for (Node node : path)
{
sf::RectangleShape rect(sf::Vector2f(50, 50));
rect.setPosition(node.x * 50, node.y * 50);
rect.setFillColor(sf::Color::Green);
window.draw(rect);
}
// Draw the start and end nodes
sf::RectangleShape startRect(sf::Vector2f(50, 50));
startRect.setPosition(start.x * 50, start.y * 50);
startRect.setFillColor(sf::Color::Red);
window.draw(startRect);
sf::RectangleShape endRect(sf::Vector2f(50, 50));
endRect.setPosition(end.x * 50, end.y * 50);
endRect.setFillColor(sf::Color::Blue);
window.draw(endRect);
window.display();
}
return 0;
}
any idea why its doing this?
I've tried to debug the code and i cant seem to find the problem. Either the code doesn't run or it just shows the same thing

C/C++ qsort an array of struct within a struct

I'm working on Kruskal's algorithm. The sorting part using the qsort function creates a strange behaviour of nodes: It order correctly by weight but changes every node's parent. This behaviour got me a stack overflow when the programs executes the FIND-SET(X) function.
Here is my code:
#include <iostream>
/*
*DISJOINT
*SETS
*/
typedef struct NODE {
int rank;
int data;
struct NODE *parent;
} NODE;
//MAKE-SET(x)
void makeSet(NODE *node) {
node->parent = node;
node->rank = 0;
}
//FIND-SET(x)
NODE *findSet(NODE *node) {
if (node != node->parent) {
node->parent = findSet(node->parent);
}
return node->parent;
}
//LINK(x, y)
void link(NODE *nodeX, NODE *nodeY) {
if (nodeX->rank > nodeY->rank) {
nodeY->parent = nodeX;
} else {
nodeX->parent = nodeY;
if (nodeX->rank == nodeY->rank) {
nodeY->rank += 1;
}
}
}
//UNION(x, y)
void unionSet(NODE *nodeX, NODE *nodeY) {
link(findSet(nodeX), findSet(nodeY));
}
/*
*GRAPH
*/
typedef struct EDGE {
NODE source;
NODE destination;
int weight;
} EDGE;
typedef struct GRAPH {
int V; //Number of vertices/nodes
int E; //Number of edges
EDGE *edge; //Array of edges
} GRAPH;
GRAPH *newGraph(int allocatedNumberOfVertices, int allocatedNumberOfEdges) {
GRAPH *graph = (GRAPH *)malloc(sizeof(GRAPH));
graph->E = 0; // intial state: no edges
graph->V = allocatedNumberOfVertices;
graph->edge = (EDGE *)malloc((allocatedNumberOfEdges) * sizeof(EDGE));
return graph;
}
void addEdge(GRAPH *graph, NODE srcNode, NODE dstNode, int weight) {
graph->edge[graph->E].source = srcNode;
graph->edge[graph->E].destination = dstNode;
graph->edge[graph->E].weight = weight;
graph->E += 1;
}
int compareEdges(const void *first, const void *second) {
const EDGE *firstEdge = (const EDGE *)first;
const EDGE *secondEdge = (const EDGE *)second;
if (firstEdge->weight == secondEdge->weight) {
return 0;
} else if (firstEdge->weight > secondEdge->weight) {
return 1;
} else {
return -1;
}
}
/*Kruskal's algorithm - returns an array of least weighted edges*/
EDGE *getMinimumSpanningTree(GRAPH *graph) {
int V = graph->V;
int E = graph->E;
int resultE = 0;
EDGE *result = (EDGE *)malloc(E * (sizeof(EDGE)));
//create a disjoint-set for every node
for (int e = 0; e < E; e++) {
makeSet(&(graph->edge[e].source));
makeSet(&(graph->edge[e].destination));
}
//sort edges of graph into nondecreasing order by weight
qsort(graph->edge, graph->E, sizeof(struct EDGE), compareEdges);
//finds a safe edge to add to the growing forest
for (int e = 0; e < E; e++) {
if (findSet(&(graph->edge[e].source))->data != findSet(&(graph->edge[e].destination))->data) {
result[resultE++] = *graph->edge;
unionSet(&(graph->edge[e].source), &(graph->edge[e].destination));
}
}
return result;
}
void KruskalDemo() {
GRAPH *graph = newGraph(6, 9);
NODE node[6];
for (int i = 0; i < 6; i++) {
node[i].data = i;
}
addEdge(graph, node[0], node[1], 3);
addEdge(graph, node[1], node[2], 1);
addEdge(graph, node[2], node[3], 1);
addEdge(graph, node[3], node[0], 1);
addEdge(graph, node[3], node[1], 3);
addEdge(graph, node[3], node[4], 6);
addEdge(graph, node[4], node[2], 5);
addEdge(graph, node[4], node[5], 2);
addEdge(graph, node[5], node[2], 4);
EDGE *MST = getMinimumSpanningTree(graph);
//we expect to have 5 vertices
for (int i = 0; i < 5; i++) {
printf("weight(%d, %d) = %d\n", MST->source.data, MST->destination.data, MST->weight);
}
}
int main() {
KruskalDemo();
return 0;
}
I solved: The problem was the algorithm and the fields of struct edge were not pointers:
Changed that:
typedef struct EDGE {
NODE source;
NODE destination;
int weight;
} EDGE;
to that:
typedef struct EDGE {
NODE *source;
NODE *destination;
int weight;
} EDGE;
And the algorithm to:
for (int e = 0; e < E; e++) {
if (findSet(graph->edge[e].source)->data != findSet(graph->edge[e].destination)->data) {
result[resultE++] = graph->edge[e];
unionSet(graph->edge[e].source,graph->edge[e].destination);
}
}

C++ structures containing structures SIGSEGV

Let me paste the code first
#include <iostream>
#include <algorithm>
#define MAX 100
using namespace std;
int index;
struct node{
int key;
struct node *up;
int rank;
};
struct edge{
struct node *start, *end;
int weight;
};
struct graf{
struct node *tops[MAX];
int topsAmount;
struct edge *edges[MAX];
int edgesAmount;
};
void makeSet(struct node *z, int key){
z->up = z;
z->rank = 0;
z->key = key;
}
struct node *findSet(struct node *x){
if(x!=x->up)
x->up = findSet(x->up);
return x->up;
};
struct node *returnPath(struct node *x){
cout<<"klucz: "<<x->key<<" ranga: "<<x->rank<<endl;
if(x!=x->up)
{
returnPath(x->up);
}
}
void link(struct node *x, struct node *y){
if(x->rank>y->rank)
{
y->up=x;
}
else
{
x->up=y;
if(x->rank == y->rank)
y->rank++;
}
}
void unionFun(struct node *x, struct node *y){
link(findSet(x), findSet(y));
}
bool acompare(edge lhs, edge rhs) { return lhs.weight < rhs.weight; }
struct edge *MSTKruskal(struct graf *G){
struct edge *A = new edge[MAX];
index=0;
for(int i=0; i<G->topsAmount; i++)
{
makeSet(G->tops[i],0);
}
sort(G->edges[0], G->edges[G->edgesAmount-1], acompare);
for(int i=0; i<G->edgesAmount; i++)
{
if(findSet(G->edges[i]->start) != findSet(G->edges[i]->end))
{
A[index].start = G->edges[i]->start;
A[index].end = G->edges[i]->end;
A[index].weight = G->edges[i]->weight;
index++;
unionFun(G->edges[i]->start, G->edges[i]->end);
}
}
return A;
}
int main()
{
struct node *values[11];
for(int i=0; i<10; i++)
{
values[i] = new node;
makeSet(values[i],i);
}
unionFun(values[0], values[1]);
unionFun(values[2], values[3]);
unionFun(values[1], values[2]);
unionFun(values[5], values[6]);
unionFun(values[7], values[8]);
unionFun(values[3], values[5]);
unionFun(values[0], values[7]);
for(int i=0; i<10; i++)
{
cout<<"sciezka klucza "<<i<<endl;
returnPath(values[i]);
}
struct graf *Graf = new graf;
for(int i=0; i<10; i++)
{
Graf->tops[i] = values[i];
Graf->topsAmount++;
}
struct edge *Edges = new edge[4];
Edges[0].start = values[1];
Edges[1].start = values[2];
Edges[2].start = values[3];
Edges[3].start = values[4];
Edges[0].end = values[5];
Edges[1].end = values[6];
Edges[2].end = values[7];
Edges[3].end = values[8];
Edges[0].weight = 10;
Edges[1].weight = 12;
Edges[2].weight = 11;
Edges[3].weight = 13;
Graf->edges[0] = Edges[0]; //this line was deleted after I found out that I can't compile it
Graf->edges[0]->weight = 0;
return 0;
}
I want to set new graf so firstly in for loop I add tops to my structure and it works then I want to add edges and problem appears. I thought I can just create another array of structures edge and then just set same array in Graf on same values (Graf->edges[0] = Edges[0]; last lines of the code) but it didn't compile, so I wanted to set every value of structure edge in array Graf separately (start = start, end = end etc) but debugger shows SIGSEGV on last line (Graf->edges[0]->weight = 0;) how can I fix it?
Edges[0] has type edge, but Graf->edges[0] has type edge*, i.e. the types are incompatible, which is why the assignment is not allowed.
You probably want to take the address of Edges[0] like so:
Graf->edges[0] = &Edges[0];

C++ Implementation of Held-Karp and speed

I'm trying to speed up my implementation of the Held-Karp Algorithm and I've been trying to figure why after nine points, it starts to become increasingly slow. I'm also utilizing xlib to help with illustrating the graph but I don't think that's the issue.
double GetMinimumRoute(int startVertex, std::vector<int> Set, Node* root)
{
printf("%d\n", CountRecursive);
CountRecursive++;
if(Set.empty())
{
Node node;
root->Nodes.clear();
root->Nodes.push_back(node);
root->Nodes.at(0).Value = Vertices[0];
root->Nodes.at(0).Selected = true;
root->CountNodes = 0;
return AdjancyMatrix[startVertex][0];
}
double totalCost = 999999999;
int selectedIndex = 0;
//root->Nodes.clear();
for(unsigned int i=0; i<Set.size(); i++)
{
Node node;
node.Selected=false;
root->Nodes.push_back(node);
root->Nodes.at(i).Value = Set.at(i);
int costOfVisitingCurrentNode = AdjancyMatrix[startVertex][Set.at(i)];
std::vector<int> newSet(Set);
newSet.erase(newSet.begin()+i);
int costOfVisitingOtherNodes = GetMinimumRoute(Set.at(i), newSet, &(root->Nodes.at(i)));
int currentCost = costOfVisitingCurrentNode + costOfVisitingOtherNodes;
if(totalCost > currentCost)
{
totalCost = currentCost;
selectedIndex = i;
}
}
root->Nodes.at(selectedIndex).Selected = true;
return totalCost;
}

C++ Console Application1.exe has triggered a breakpoint

when I try to set
cub.SetArray(cube);
I get an error
Console Application1.exe has triggered a breakpoint
What I'm doing wrong? When I try to debug cub -> cubesarray I get size -842150451. I don't understand why.Here's my all code
class Cube{
public:
static const int Change_ARRAY = 5;
private:
string color;
int size;
int *walls;
int n; // current size of array
int maximumsize; // maximum size of array
void Increase(int many);
public:
Cube(int maximumsize = 0);
~Cube();
void SetWalls(int wall);
void SetColor(string color);
void SetSize(int size);
string GetColor(){return color;}
int GetWalls(int i){return walls[i];}
int GetSize(){return size;}
int GetN(){return n;}
};
Cube::Cube(int maximumsize):n(0), maximumsize(maximumsize), size(size), walls(NULL){
if(maximumsize > 0){
walls = new int[maximumsize];
}
}
Cube::~Cube(){
if(walls){
delete [] walls;
}
}
void Cube::Increase(int many){
if(many > maximumsize){
int *newest = new int[many];
for(int i=0; i<n; i++)
newest[i] = walls[i];
delete [] walls;
walls = newest;
maximumsize = many;
}else if( many < maximumsize){
int *newest = new int[many];
for(int i=0; i<many; i++)
newest[i] = walls[i];
delete [] walls;
walls = newest;
n = maximumsize = many;
}
}
void Cube::SetWalls(int wall){
if(n == maximumsize) Increase(n + Change_ARRAY);
walls[n] = wall;
n++;
}
void Cube::SetColor(string color){
this->color = color;
}
void Cube::SetSize(int size){
this->size = size;
}
class CubesArray{
public:
static const int Change_Array = 5;
private:
Cube *cubesarray;
int currentsize; // current size of array
int maxsize; // maximumsize
void Change (int kk);
public:
CubesArray(int maxsize = 1);
~CubesArray();
void SetArray(Cube c);
Cube GetArray(int ind){return cubesarray[ind];}
int GetCsize(){return currentsize;}
};
CubesArray::CubesArray(int maxsize):cubesarray(NULL), currentsize(0), maxsize(maxsize){
if(maxsize > 0){
cubesarray = new Cube[maxsize];
}
}
CubesArray::~CubesArray(){
if(cubesarray){
delete [] cubesarray;
}
}
void CubesArray::Change(int kk){
if(kk > maxsize){
Cube *newarr = new Cube[kk];
for(int i=0; i<currentsize; i++)
newarr[i] = cubesarray[i];
delete [] cubesarray;
cubesarray = newarr;
maxsize = kk;
}if(kk < maxsize){
Cube *newarr = new Cube[kk];
for(int i=0; i<kk; i++)
newarr[i] = cubesarray[i];
delete [] cubesarray;
cubesarray = newarr;
currentsize = maxsize = kk;
}
}
void CubesArray::SetArray(Cube cub){
if(currentsize = maxsize) Change(currentsize + Change_Array);
cubesarray[currentsize] = cub;
currentsize++;
}
void Read(CubesArray & cub);
int main(){
CubesArray cub;
Read(cub);
system("pause");
return 0;
}
void Read(CubesArray & cub){
string color;
int size;
int i=0;
Cube cube;
ifstream fd(Data);
while(!fd.eof()){
fd >> color >> size;
cube.SetSize(size);
cube.SetColor(color);
cout << cube.GetColor() << " " << cube.GetSize() << " ";
while(fd.peek() != '\n' && !fd.eof()){
int w;
fd >> w;
cube.SetWalls(w);
cout << cube.GetWalls(i) << " ";
cub.SetArray(cube); // when I set cube to cub I get this error!!!
i++;
}
cout << endl;
fd.ignore();
}
}
Change:
if(currentsize = maxsize)
To:
if(currentsize == maxsize)
In addition, here is your real problem:
You have no copy-constructor in class Cube, so the walls array is not properly copied whenever you send a Cube instance by value, e.g., cub.SetArray(cube).
You must define it as follows:
Cube::Cube(const Cube& cube):n(cube.n),maximumsize(cube.maximumsize),size(cube.size),wall(NULL)
{
if (maximumsize > 0)
{
walls = new int[maximumsize];
for (int i=0; i<maximumsize; i++)
wall[i] = cube.wall[i];
}
}
And you have no assignment-operator in class Cube, so the walls array is not properly copied whenever you assign one Cube instance into another, e.g., cubesarray[currentsize] = cub.
You must define it as follows:
Cube& Cube::operator=(const Cube& cube)
{
n = cube.n;
maximumsize = cube.maximumsize;
size = cube.size;
wall = NULL;
if (maximumsize > 0)
{
walls = new int[maximumsize];
for (int i=0; i<maximumsize; i++)
wall[i] = cube.wall[i];
}
return *this;
}
BTW, in the copy-constructor, you can simply call the assignment-operator (remove coding redundancy):
Cube::Cube(const Cube& cube)
{
if (this != &cube)
*this = cube;
}
Your Cube class violates the rule of three. Look here:
void CubesArray::SetArray(Cube cub){ // calls copy constructor
That call creates a copy of your Cube class. Your Cube class is not safely copyable. Please see this and scroll down to the Managing Resources section: What is The Rule of Three?
You should pass Cube by reference or const reference, not by value. Doing so may correct the error you're having now, but still, your class is faulty.