Access violation reading while using object pointers - c++

At the beginning, my program creates a structure and a class that contain a struct and two int variables.
#define fullwidth 200
#define fullheight 200
typedef struct tiles
{
unsigned char red, green, blue;
char* name;
}tiles;
class Units
{
public:
int X_Pos;
int Y_Pos;
tiles MapColour;
}
After that, in the main part, I create a 2-dimensional array to use tiles as RGB containers for display, and an array of object pointers to follow any changes in the declared objects.
int i, j;
tiles fieldd[fullwidth][fullheight];
Units* DetectorField[fullwidth][fullheight];
Units Objects[10];
After that (now in main()), I upload both of the arrays with valid values, avoiding issues about that.
for (j=0;j<fullheight;j++)
{
for (i=0;i<fullwidth;i++)
{
fieldd[i][j] = BASE;
DetectorField[i][j] = NULL;
}
}
Same with the objects + adding object memory adress for pointers to be able to identify them through DetectorField:
for (i=0; i<9;i++)
{
Objects[i].X_Pos = i+2; //just some values, not important yet
Objects[i].Y_Pos = 2*i+2;
DetectorField[Objects[i].X_Pos][Objects[i].Y_Pos] = &Objects[i];
}
Most certainly, this is okay yet. But the problem comes now! In the next piece of codes, I check every elements of DetectorField; if the chosen element isn't NULL yet (which obviously means that it can be only the memory adress of an object, since it couldn't get any other values - if I know well), then put the MapColour variable to the array of structures.
for (j=0;j<fullheight;j++)
{
for (i=0;i<fullwidth;i++)
{
if(DetectorField[i][j] != NULL)
{
fieldd[i][j] = DetectorField[i][j]->MapColour;
}
}
}
At this point, MSVC gives this error message when I try to run it: Unhandled exception at 0x00411ed7 in Fallen Star.exe: 0xC0000005: Access violation reading location 0xccccccdc.
What did I do wrong? The operation inside the condition seems OK for me. Is the problem the way I use fieldd maybe?

You simply have access violation. You should debug your code, by Stepping Into and Stepping Over to find out where the access violation is coming from. The access violation says, you are trying to refer to NULL references. Make sure you allocate memory to your Objects before accessing them.
You have a for loop that assigns DetectorField[i][j] = NULL, meaning location [i][j] is a NULL reference. And then you have a reference DetectorField[Objects[i].X_Pos][Objects[i].Y_Pos]. You might have some access violation right there.

This loop:
for (i=0; i<9;i++)
{
Objects[i].X_Pos = i+2; //just some values, not important yet
Objects[i].Y_Pos = 2*i+2;
DetectorField[Objects[i].X_Pos][Objects[i].Y_Pos] = &Objects[i];
}
Does not seem to do a full initialization, because there are 10 elements in Objects and you only initialize 9 of them.
I think you want
for (i=0; i<10; i++)
Or even better
for (i=0; i<(sizeof(Objects)/sizeof(Objects[0])); i++)

Related

Pointer dereference causes error when using arrow operator

I'm trying to use pointers (because I need them), but for some reason, I don't understand them. (The explanation is under the code snipped)
void Spiel::SetFigureToField(Figur *figur)
{
*figur->teampos = *figur->*spieler->GiveTeamPos();
figur->teampos = figur->spieler->GiveTeamPos();
figur->pos = figur->teampos;
this->spielfeld[figur->Startpoint].Figuren.push_back(figur);
std::vector<Figur*>* figs = &figur->spieler->SpawnField;
for (int i = 0; i < figs.size(); i++) //find figure in spawnfield and erase it
{
if (*figs[i] == figur)
{
*figs.erase(*figs.begin() + i);
}
}
}
struct Figur
{
Spieler* spieler{};
int Startpoint{}; //startpoint on spielfeld
int teampos{0}; //pos in Array | 0 best - 4 worst | 5 spawnfield
int pos{};
int id{};
void reset(int team, int pos)
{
if (team == 0) this->Startpoint = 0;
else this->Startpoint = 21;
teampos = pos;
}
};
class Spieler
{
public:
Spieler(std::string wuerfelS, int team);
//Stats
int Wins{ 0 };
int AnzahlWuerfen{ 0 };
//for game
int FigursActive{ 0 }; //keepstrack of the figurs on field
Wuerfel wuerfel{};
std::vector<Figur>figuren{};
std::vector<Figur*>SpawnField{};
Figur* ZielFeldArray[4];
int GiveTeamPos();
};
Okay, the first function is my problem point.
Explanation of how it should function: So a Figur (pointer) gets passed in the function and it should place to a gamefield.
What I understand: I want to edit the teampos in the figur. So what i learn is that I should dereference it (so I get the values from the memory address), but if i do *figur->teampos it just gives me an error.
The other one:
std::vector<Figur*>* figs = &figur->spieler->SpawnField;
With this I should get the pointer of the SpawnField vector. What I thought is that i have to dereference it to use the values and methods of vectors. *figs.size() This is what I tried and it gives an error.
It's clear that I don't understand pointers, but every tutorial says: if you have a pointer you have to dereference it to access the values (okay makes sense), but it doesn't function
I'm trying use pointers (because i need them), but for some reason i dont understand them.
How can you be so sure you need them if you don't understand them? I really mean this question, as many programmers, even good one, will be convinced that a solution is the best, but in reality a misunderstanding of the problem is at the core of the issue instead.
What i understand: I want to edit the teampos in the figur. So what i learn is that i should dereference it (so I get the values from the memory address), but if i do *figur->teampos it just gives me an error.
C++ has two dereferencing operators. The unary star *ptr and the arrow ptr->. If you use the arrow figur->teampos then you already deferencence figur here. ptr->member is semantically equivalent to (*ptr).member.
The other one: std::vector<Figur*>* figs = &figur->spieler->SpawnField; with this i should get the pointer of the SpawnField vector. What I thought is that i have to dereference it to use the values and methods of vectors. *figs.size() This is what i tried and it gives an error.
To access the vector's member, you should use the arrow: figs->size() as the star operator cannot access members directly.
Same thing when indexing. doing vec_ptr[1] will do the [] operator on the pointer, but should be on the vector itself. You will need (*vec_ptr)[1].

C++ Threading with multidimensional vectors - access violation

I'm currently trying to get work done in a threaded member function of my class. Therefore it gets a 2d array as parameter and fills it in the member function. This gets repeated multiple times. Right after spawning the first thread I get an error with either read or write access violation. I tried different approaches to solve it, but can't get it to work. While I found nearly any problem already solved here, in this case I was unsuccessful finding something for quite a while now.
void myClass::process(Vector3D& out_stack, long filterFaktor){
long rowSize = this->input2D.size();
long colSize = this->input2D.at(0).size();
int filterPerRowCount = ceil((double)rowSize / filterFaktor);
int filterPerColCount = ceil((double)colSize / filterFaktor);
std::vector<std::thread> threadPool;
//create new filter
long currentrow = 0;
while (currentrow < rowSize) {
long currentcol = 0;
while (currentcol < colSize) {
Filter* nextFilter = &this->createNextFilter(currentrow, currentcol, filterPerRowCount, filterPerColCount);
out_stack.push_back(Vector2D());
Vector2D* nptr = &out_stack[out_stack.size()-1];
//Here we are calling the thread which leads to the access violation
threadPool.push_back(std::thread(&myClass::nextProcess, this, nextFilter, nptr, rowSize, colSize));
currentcol += filterPerColCount;
}
currentrow += filterPerRowCount;
}
//wait until threads have finished
for (int iThread = 0; iThread < threadPool.size(); iThread++) {
threadPool[iThread].join();
}
}
void myClass::nextProcess(Filter* nextfilter, Vector2D* out_Map, long rowCount, long colCount){
//Loops this part -> creates the rows and pushes them in the out_Map
std::vector<double> nextRowInMap;
//... Calculates sum
nextRowInMap.push_back(sum);
//Push row in vector -> This is where the error occurs
out_Map->push_back(nextRowInMap);
}
typedef std::vector<double> Vector1D;
typedef std::vector<Vector1D> Vector2D;
typedef std::vector<Vector2D> Vector3D;
I think I'm just missing knowledge in using Pointers in C++, cause I'm new to it.
Thanks in advance & best regards
EDIT
Tried it now this way, still doesn't work:
out_stack.push_back(Vector2D());
long index = out_stack.size() - 1;
threadPool.push_back(std::thread(&myClass::nextProcess, this, nextFilter, &out_stack, index, rowSize, colSize));
And in nextProcess:
out_stack->at(index).push_back(nextRowInMap);
EDIT
Solved with mutex. Additionally I needed to pass the filter not on reference.
You error is here:
out_stack.push_back(Vector2D());
Vector2D* nptr = &out_stack[out_stack.size()-1];
There is no guarantee that the object stays at the same address when you modify the vector.
When the vector has to grow it can allocate the internal memory on another address and move the objects in the vector to a new address. So the pointer can get invalid on the next push_back
You should pass the vector and index to the thread and access it each time you need it
out_stack[index].push_back(...)
It may be that after out_stack[index] and before push_back the vector gets modified and you are also operating on invalid memory. So you should protect accessing/modifying the vector with a std::mutex. I am not sure on that last part though if there is some thread safety guarantee there I don't know of.

How do I deallocate this in C++?

I create a 2D array of Nodes (Node class is in a separate file) and i'm wondering how to deallocate exactly this (below). I've tried many ways and mem leaks still appear.
board = new Node * [r];
//creats a column for each element in the row
for(int i = 0; i < r; i++) {
board [i] = new Node [c];
}
(r is the rows and c is the cols)
I've done this:
for(int i = 0; i < r; i++) {
delete [] board[i];
}
delete [] board;
But apparently it's not enough
The code you have is correct and sufficient. However, it would be better to use RAII so that you do not need to explicitly call delete at all (perhaps not even new). For example, you could create a std::vector<std::vector<Node>>, or better still, some sort of matrix class (not in the standard library, unfortunately).
Your solution is the correct way to free two dimensional array. However you may still get a memory leak if Node uses dynamic memory and it's destructor is not properly defined.
As others have said, you're correctly pairing up all your new[]s and delete[]s: assuming no errors occur, the memory allocated by this code will be correctly deallocated.
The only issue is that errors may occur, and in particular exceptions may be thrown:
new[] can throw an exception if it fails to allocate memory (doesn't normally happen on desktop OSes, but you should still write code as if it does.)
Node's constructor may throw. Even if you've designed the constructor not to throw you generally shouldn't take advantage of that knowledge. Just write code as if throws.
In fact, you should just generally write code as if pretty much anything can throw. For more detailed info on writing exception safe code, and on what the exceptions to this rule are you can read the info at http://exceptionsafecode.com
The best way to make this code exception safe is to use RAII. For example use a vector instead of new[]/delete[].
Using an array of pointers and a separate allocation for each row makes sense for 'ragged' arrays, where each row can be a different length. In your case you have rectangular array, so you can use a single allocation for the whole thing.
std::vector<Node> board(rows*columns);
board[row_index*columns + column_index] // replaces board[row_index][column_index]
You can hide the implementation by putting this in a class:
class Board {
std::vector<Node> board_data;
public:
const int rows;
const int columns;
Board(int rows_, int columns_)
: board_data(rows_*columns_)
, rows(rows_)
, columns(columns_)
{}
struct board_index { int row, column; };
Node &operator[](board_index i) {
assert(0 <= i.row && i.row < rows);
assert(0 <= i.column && i.column < columns);
return board_data[i.row * columns + i.column];
}
};
Board board(r, c);
with the above implementation you replace board[i][j] with board[{i, j}].
board[{i, j}] = ... // assign to a place on the board
board[{i, j}].foo(); // call a Node method
std::cout << board[{i, j}]; // print a Node
// etc.

Access violation when accessing vector element's member function

I am coding an MFC applcation using VS2012.
I have a vector of Bitmap*, I insert elements in a for loop, and then, if I try to access some element's function outside the loop it will give me an access violation.
The strange thing is if I try to access it inside the loop, it works just fine.
In both examples m_VectorImageNames is already filled with some image files paths, it is not the problem.
The following code gives the access violation (at the last line):
std::vector<Bitmap *> vectorImages;
for (int i = 0; i < nImages; i++)
{
Bitmap img(m_VectorImageNames[i]);
vectorImages.push_back(&img);
}
int imgWidth= vectorImages[0]->GetWidth();
If I put the GetWidth inside the loop, it returns the correct value:
std::vector<Bitmap *> vectorImages;
for (int i = 0; i < nImages; i++)
{
Bitmap img(m_VectorImageNames[i]);
vectorImages.push_back(&img);
int imgWidth= vectorImages[0]->GetWidth();
}
I have tried a few things already, with no success:
Initializing the vector with the size it will have and then inserting each bitmap in its corresponding position (with hope that it was an allocation problem).
Looping using iterators
Making the vector a class member variable
Does anyone have a clue of what may be happening?
The BitMap object img is defined on the stack inside the loop. The pointer to img is pushed into the vector. Then the memory storage that the pointer elements point to in the vector is lost once the loop has terminated.
Use new (the operator for dynamic memory allocation) to store the bitmaps.
for (int i = 0; i < nImages; i++)
{
Bitmap *img = new BitMap(m_VectorImageNames[i]);
vectorImages.push_back(img);
...
}
Possibly better (instead of using raw pointers) would be to use a memory-managed pointer such as std::shared_ptr. This depends on your requirements.

Multi-Dimensional Arrays--> Null Object Pointers

I am trying to develop a C++ application. Part of the Application is meant to create and initiate some properties of an Object and then store the object in a multi-dimensional array. Problem is after Object creation and storing the objects in the array, retrieving the Object values gives me pointers to NULL.
Please see code below for exact implementation:
Cell** TestMain::convertToMatrix(){
//char[] lengthArr = arra[0];
//int[][] temp
int rowCount = getCurrentRowCount(); // Gives the row count of the multi-dimensional array
int colCount = getCurrentColCount(); // Gives the column count of the multi-dimensional array
Cell** cellList;
cellList = new Cell*[rowCount];
for (int rowIter=rowCount-1;rowIter>=0; rowIter-- ){
cellList[rowIter] = new Cell[colCount];
for (int colIter=colCount-1;colIter>=0;colIter--) {
Cell *currentCell = new Cell(arra[rowIter][colIter],rowIter,colIter);
//Calculate weights
if (0==currentCell->getValue()) currentCell->setWeight(0);
if (1== currentCell->getValue()) {
if (isEdge(rowIter,colIter)) {
currentCell->setWeight(1);
}
else {
//currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter]->getWeight(),cellList[rowIter+1][colIter+1]->getWeight(),cellList[rowIter][colIter+1]->getWeight() ) );
currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter].getWeight(),cellList[rowIter+1][colIter+1].getWeight(),cellList[rowIter][colIter+1].getWeight() ) );
}
}
cellList[rowIter][colIter] = *currentCell;
}
}
return cellList;
}
`
Here is the code that performs the checking later in the code:
void StrawberryMain::printField(Cell** arrayOfCells) {
int row=0;
int column=0;
int maxRowCount= getCurrentRowCount();
int maxColCount = getCurrentColCount();
for (;row<maxRowCount;row++) {
Cell *cellArr = arrayOfCells[row];
for (;column<maxColCount;column++) {
Cell currentArrayCell = cellArr[column];
/*if (currentArrayCell==NULL){ // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why?
printf("Returned Pointer for Cell was NULL");
}
else { */
printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());
/
//}
printf("\n");
}
}
When I run the program I get a whole load of nulls printed on my screen as output.( One null for every object supposed stored in the array
I come from a Java background ( although I have dabbled in QT C++ before) so I am a bit miffed why this is happening. As much as I would appreciate an answer I would value an explanation as to why this happens ( or a link which explains why this happens) as I really want to understand the workings of the Language.
Thanks in anticipation.
There are several issues in your code.
As already stated in comments, you have a memory leak issue.
if (currentArrayCell==NULL){ // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why?
currentArrayCell as declared in your code is a Cell object. Not a pointer to one. So you aren't comparing if a pointed to Cell is NULL. That line is trying to compare if a Cell == 0. And since you apparently haven't defined an equality operator that could work with a Cell and 0 the compiler raises that error.
With that in mind, you should note that the line Cell currentArrayCell = cellArr[column];
is actually creating a copy of a Cell. It may not be important this time. But if you write similar code where you would modify currentArrayCell, then you would find that any changes are only made to the local copy and not to the element in cellArr.
This line:
printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());
is most likely not doing what you wanted. s% means you must pass a string (meaning something like a const char*). However, based on your other code I'm guessing that those member functions are returning integers. printf is a low level tool and does not have the ability to convert between data types in that manner. You either need to use the appropriate format specifier for the data type (such as %d for int) or convert the values before passing them to printf.
So what happens when you use the wrong format specifier is that printf tries to byte-wise interpret whatever you actually passed as whatever type the format specifier implies. In your case, it's trying to interpret integers as character pointers. I'm actually surprised this isn't causing a crash instead of just printing nulls.
just to give you an idea
template<typename T>
struct array {
array(int m, int n) {
size_[0] = m, size_[1] = n;
data_.resize(m*n);
}
T* operator[](int i) {
return &data_.front() + i*size_[1];
}
private:
stdvector<T> data_;
size_t size_[2];
};
It seems clear from your code that you're a C guy doing C++, so here are some classes that should be aware of in light of your goals.
Boost's ublas has a matrix implementation that would be a generally superior alternative to creating your own implementation.
Baring that, at bare minimum you should probably be working with vectors instead of dynamically created arrays to reduce the potential for memory leaks.