Data is lost from an array when trying to access it - c++

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).

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.

Why would this example give a segmentation fault?

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.

How to remove elements from dynamically allocated array?

I have a dynamically allocated array :
myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];
I would like to loop through all elements in this array and remove these that will meet my condition (e.g. too big rectangle).
I have been thinking that I can loop through this array and get the number of elements that would satisfy my condition and then allocate a new array. But how can I 'transfer' these 'wanted' elements into my new array ?
Just for the record: I cannot use STL containers.
myRectangle * lastRectanglesArray = new myRectangle[lastMaxLabel];
// initialize the entries in the lastRectanglesArray
// create a temporary array which contains info about each individual
// entry. namely, it only holds info about whether the entry should
// be kept, or deleted.
// we also use the 'entries' value, which is the number of entries
// in the new array
bool * entriesToKeep = new bool[lastMaxLabel];
int entries = 0;
// check each entry, and mark whether it should be kept or deleted
for (int i = 0; i != lastMaxLabel; ++i) {
// check whether the entry should be kept or deleted...
// here, i just put a function with signature like:
// bool shouldKeepRectangle(const myRectangle &);
entriesToKeep[i] = shouldKeepRectangle(lastRectanglesArray[i]);
if (entriesToKeep[i]) ++entries;
}
// create a new array that will contain the entries that should be kept
myRectangle * rectanglesArray = new myRectangle[entries];
// assign the entries in the new array
for (int i = 0, j = 0; i != lastMaxLabel && j != entries; ++i) {
if (entriesToKeep[i])
rectanglesArray[j++] = lastRectanglesArray[i];
}
// free the memory held by the temp array
delete [] entriesToKeep;
// if the old array is not needed anymore, delete it
delete [] lastRectanglesArray;
// and here you have rectanglesArray, a brand new array that contains
// only the elements that you need.
Just move the next array location over the one that needs to be deleted, and shift everything over til the end of the array.
Yours look like the perfect case for using a Linked List. You would however have to do away with the new myRectangle[lastMaxLabel] part as you would have to implement it as pert of your Insert() function.
This way you would not require to transfer the wanted elements into a new array, but just delete the unwanted element.
Any more light on your use-case would help us to think of better alternatives.
I agree with Michael Chinen - use std::vector instead. You'll avoid lots of other potential problems this way. If you really want to use dynamic arrays, see this question: Remove an array element and shift the remaining ones
if you have a big amount of data in array that will be a problem for shifting using loop
maybe you should build your own array management class (find,add,deleteAt,etc).
my suggestion use link list node method.. it will be faster rather then you use loop for shifting.

Pointer address does not change in a link list

My problem is q->next always prints the same address, but I assigned q = &x;. Why it is not printing different addresses?
#include <stdio.h>
class Node
{
public:
int val;
Node *next;
Node(int v,Node *p) { val=v, next=p; }
};
int main()
{
Node head(0, NULL);
Node *q = &head;
int i = 5;
while (i>0)
{
Node x(i * 10, q);
q = &x;
printf("# %d %p\n", q->val, q->next);
i--;
}
}
In the first iteration of the loop, q contains the address of head. On each subsequent iteration, q contains the address of x.
This means that on the first iteration, q->next yields the address of head and on each subsequent iteration, q->next yields the address of x. However, x is created inside the loop, on the stack. Since there is no change to the stack inbetween, the x object always appears at the same place on the stack.
So I'd expect the program to print first the address of head and then four times the address of the four x objects (which all happen to be allocated at the same position of the stack).
I think the reason is that, within the while loop, you declare x on the stack. Then after the end of the while loop has been reached, the variable gets "destroyed". In the subsequent iteration, however, x gets reserved on the stack again using the exact same (stack) memory place.
Note that you won't get a linked list with valid pointers. You need to create Node instances on the heap using 'new' operator.
EDIT:
If you don't want to allocate memory on the heap you can use the "Linked lists using arrays of nodes" approach descriped here. The drawback is, however, that you need to know the maximum number of nodes in advance.
This has to do with the way x is allocated: It is a local variable inside the main function. That means it is allocated on the stack, at a specific position. You are reusing the same piece of memory all the time. Instead, try allocating memory for new nodes (new).
Your are creating the Node on the stack - try using new.
x is a local variable in the while loop. Its lifetime is only one iteration of the loop.
You should dynamically allocate the Node objects like so :
Node* x = new Node(value, next);
so their lifetime lasts until you de-allocate the object :
delete x;
Node x is being created on the stack, each time you go round your loop it will be getting created and then destroyed again at the end of the block. And each time round the loop it will be being created in the same location.
You probably want:
Node *x = new Node( i*10, q );
q = x;
You keep setting next to q:
Node x(i * 10, q);
Your x node is allocated on the local stack, not on the heap, so as your variable gets recycled on each loop iteration it recieves the same local address. To create i = 5 uique nodes you need to allocate object on heap using new() operator. You would also to add code to destoy your allocated objects afterwards.
example:
Node * px = new Node(i*10, 1);