Why would this example give a segmentation fault? - c++

Does anyone know why this would give me a segmentation fault?
cell.h
struct cell{
bool filled;
bool isParent;
//float px,py,pz,s;
bool cx,cy,cz;
unsigned char r,g,b;
vect norm;
struct cell* parent;
struct cell* child;
cell(bool cxx=0, bool cyy=0, bool czz=0);
void open_read(string);
};
cell.cpp
cell::cell(bool cxx, bool cyy, bool czz)
{
cell childs[8]; // these lines creates a segmentation fault
child = &childs[0]; // these lines creates a segmentation fault
cx=cxx;
cy=cyy;
cz=czz;
norm = vect(0,0,0);
norm.normalize();
isParent=false;
filled=true;
}
If this is the wrong way to do this could anyone point me in the right direction as to how I could store a single pointer to the first element of child[8] instead of storing 8 pointers as it is quite memory intensive.

You are trying to set up an infinite recursion. The constructor of cell allocates an array of 8 cell objects, whose construction in turn invokes the constructor of cell with default arguments.
Each stack frame consumes space, and sooner or later the stack will grow bigger than its size limit due to the non-terminated call recursion, eventually resulting in a segmentation fault.

When you create a single cell, that cell's constructor creates an array of 8 more cells. Each of those creates an array of 8 cells and so on and so forth. You have infinite recursion.
It is unclear why your constructor creates an array of 8 cells - you only ever take the address of the first of them. It also doesn't make sense for each cell to automatically create its own child when it is constructed. That will lead to this infinite lineage of cells.
Not to mention, at the end of your constructor, the array of cells will be destroyed and you'll be left with a pointer to an invalid object.

Related

Adding a value to a objects array c++

I have made a node object that populates in an array of 63 x 63. After the first value, it should just access an array attached to the object and put in a value in that array.
The array of objects is defined as:
node ** arr[63][63];
and my function is this:
void addValue(int x, int y, float value)
{
node a = ** arr[x][y];
a.valueList[a.size] = value;
a.size = a.size + 1;
}
The idea is that if there is already a node in the array(when the function is called it can be assumed that there already is one), to add the value to "valueList" on the node that already exists at that spot.
here is how it is called in main:
if(!isValid(arr[xCount][yCount]))
{
node a(0, false, xCount, yCount);
addToArray(&a);
myFile.read((char *) &dataIn, 4);
yCount++;
}
else
{
myFile.read((char *) &dataIn, 4);
addValue(xCount, yCount, dataIn);
yCount++;
}
addValue function is crashing the program, and is not properly adding the value to the array attached to the object. I am guessing it might have something to do with how I am accessing the array "arr[][]".
The whole ** part of the definition of arr, as well as in the assignment to a -- you don't mention these at all in the text of your question. This leads me to suspect that you didn't actually mean to put them there. It sounds like you want a 2D array of nodes, rather than a 2D array of pointers to pointers to nodes. Indeed if you missed that and didn't allocate the nodes and pointers to nodes for the pointers to pointers to nodes to point to, then you'll get a segmentation fault.
BTW, also watch out for a being a copy of the array element, changes to which won't get propagated to arr.

Can't keep dynamically allocated memory consistent after return

I'm working on a chess-playing program. As part of it, I wrote a static method that is supposed to recursively operate on its input by calling itself with varied versions of the board, a Piece * board[8][8], and pass back the the location of the "best" version of the board inside a std::unique_ptr, which is the return type of the method.
Node is defined as such:
class node
{
public:
node();
~node();
std::unique_ptr<node> l;
std::unique_ptr<node> r;
std::unique_ptr<node> m;
node * best;
int bestval;
Piece * (*board)[8];
};
The goal is to eventually have the result of the initial call to the recursive method contain a "best" value which links to the whole chain of best path choices through the chessboard. I would then draw the series of board states that result.
As part of this, the board must be preserved. Whichever board "wins" at each recursive step gets copied to dynamic memory, and the board pointer of the return ( Piece * (*board)[8] in the node declaration) is set to this dynamically allocated memory.
This is done like so:
std::unique_ptr<node> ret (new node);
Piece *** reboard = new Piece**[8];
for (int i = 0; i < 8; i++)
{
reboard[i] = new Piece*[8];
}
...code to copy values to reboard and set other ret property values...
ret->board = reboard;
return ret;
All the local values of the winning chess board are then copied to reboard. This all works fine. If I copy all the values of reboard to a global board at this stage, return, and directly draw that global board to the screen, it draws the correct result. Likewise, if I set ret->board to point to that global board and then copy values to the global board and return, it draws the correct values.
But, if I do what I've written above and try to draw ret->board, I get invalid memory access errors in my draw method, and I'm pulling my hair out trying to pin this problem down. It seems that immediately after return, the memory pointed to by reboard is reclaimed somehow. In this memory which should only be data, I see that entries into the array appear to point to code in msctf.dll, among other invalid data pointers. I thought it was being reclaimed by garbage collection, so I've even tried putting in some std::declare_reachable calls on any and every pointer I can see, but this has not helped.
Anyone notice recognize what's going on here? Shouldn't that dynamically allocated memory stick around until I free it?
std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope. No two unique_ptr instances can manage the same object.
Source: cppreference.com
In other words, you are freeing the memory as soon as you hit return, and then return garbage. Of course it'll cause an access violation to try to dereference that memory.

Data is lost from an array when trying to access it

I have declared a basic structure as below.
struct Item
{
MPoint key; //4 element double array x,y,z,w represents a point in space
Item * next = NULL;
};
I have a small array of pointers to these structures
Item * arr[3];
When an item is created, the key is defined by its location which is a unique point in 3D space.
Item hti; //create a new item struct called hti
hti.key = transf.rotatePivot(MSpace::kWorld);
Item * p_hti = &hti; //pointer to the struct
arr[0] = p_hti;
The main problem is that when i watch the arr[0] variable in my debugger, it shows the correct key values. However, as soon as I examine the data as in
double x = arr[0]->key.x;
Instead of getting the correct value for x, i get x = -9.2559631349317831e+61 every time and for all the other values in the key (x,y,z).
I assume that the strange value above represents memory that is uninitialized but it just doesn't make sense to me how the array correctly holds the value up until I try to pull the value back.
Any help would be appreciated!
In your example where you write:
Item hti; // declared on the stack
// ...
Item* p_hti = &hti; // points to item on the stack
arr[0] = p_hti; // points to item on the stack
You are causing this array to reference items that are in the current stack frame and which will be undefined after leaving this stack frame (or which could be corrupted if you perform an operation that corrupts the current stack). Is your dereference of this array happening in the same function? Or does it happen after you return "arr" from the function in which you initialized it? If the latter, that would explain your problem... the memory it references has gone out of scope. To prevent that issue, you should use dynamic memory allocation (with new) in initializing your array (you'll also need to remember to deallocate that after you are done with it with a corresponding delete).

Adding items outside of allocated array?

I have a class Set:
class Set
{
public:
//Default constructor
Set ();
//Some more functions...
private:
int *p;
const int K = 10;
int numval = 0; //Number of ints in the array
//Other variables...
};
The default constructor:
Set::Set()
{
p = new int[K]; //Allocate memory for array with 10 ints
}
If I in some other function would fill the array with 10 ints and then add an other one, what would happen? The compiler doesn't crash and I'm able to print the 11:th int. But since I havn't allocated memory for it, where is it stored?
Example:
Set1 += 5;
Would add 5 to the array with the following operator overloader.
const Set& Set::operator+=(const int x)
{
p[numval] = x; //Add next int after the last int in the array
numval++; //Increment number of ints
return *this;
}
If I in some other function would fill the array with 10 ints and then add an other one, what would happen?
You'd write into whatever memory came after the end of the array, causing undefined behaviour: perhaps causing no obvious problems, perhaps corrupting some unrelated data (or the metadata used to manage the heap), or perhaps crashing if there was no writable memory there.
But since I havn't allocated memory for it, where is it stored?
It isn't stored anywhere, in the sense of having storage allocated for it. There's just nothing to stop you writing to arbitrary memory locations beyond the end of an array. Be careful not to do that.
Computer memory is linear. It's one huge row of cells (bytes). Every cell has 2 neighbours (except the first and the last ones, obviously). Allocating memory is just an act of telling "this part is mine". It's really nothing more than a promise: you promise to not write outside your plot and in return you get promise noone else would write inside it. So what happens when you write outside of your allocated area? You break your promise. There may be someone's else's plot right next to yours, there might be unused space. Nothing really happens when you write outside your area. Real problem arises when rightful owner comes back and tries to pick up what he left - and it turns out to be something else, something you put there. (Of course it's possible that your plot lies next to something system considers important. In that case, OS stations guards on the border, and they shot to kill any trespassers on sight.)
It is your job as a programmer to make your program keep it's promises. When processes break their promises, bad things may or may not happen - to them or to other processes.

Misunderstanding of C++ array structure

I'm new to C++ and I learned with different tutorials, in one of them I found an example of code:
I have pointed by numbers of lines, that I completely do not understand;
Does this array in array or something like that?
I can understand the second call, but what is the first doing? There is already
"coordinates[blocks[num]]", aren't there? Why need again blocks(i) ?
How do you make this part of the code easier? Did struct with this arrays
don't make easier getting value from arrays?
Thanks in advance!
// Global vars
Struct Rect {
float left;
}
Rectangle *coordinates;
int *blocks;
coordinates = new Rect[25];
blocks = new int[25];
// in method storing values
const int currentBlock = 0; //var in cycle
coordinates[currentBlock].left = column;
blocks[currentBlock] = currentBlock;
//get element method
const Rect& classA::Coords(int num) const
{
return coordinates[blocks[num]]; //(2)
}
//and calling this method like
Coords(blocks[i]); //(3)
Coords(i); //(3)
// (4)
No, not really. Lots of people will think of them as arrays and even describe them as arrays, but they're actually not. coordinates and blocks are both pointers. They just store a single address of a Rect and an int respectively.
However, when you do coordinates = new Rect[25];, for example, you are allocating an array of 25 Rects and setting the pointer coordinates to point at the first element in that array. So, while coordinates itself is a pointer, it's pointing at the first element in an array.
You can index coordinates and blocks like you would an array. For example, coordinates[3] will access the 4th element of the array of Rects you allocated. The reason why this behaves the same as arrays is because it actually is the same. When you have an actual array arr, for example, and you do arr[4], the array first gets converted to a pointer to its first element and then the indexing occurs.
No, this is not an array of arrays. What it is doing is looking up a value in one array (blocks[num]) and using that to index the next array (coordinates[blocks[num]]). So one array is storing indices into the other array.
I'll ignore that this won't compile, but in both cases you are passing an int to the Coords function. The first case looks incorrect, but might not be. It is taking the value at blocks[i], passing that to the function then using that value to index blocks to get another value, then using that other value to index coordinates. In the second case, you are just passing i, which is being used to index blocks to give you a value with which you index coordinates.
That's a broad question that I don't think I can answer without knowing exactly what you want to simplify and without seeing some real valid code.