access violation in deleting a 2d array - c++

I have a 2d array of object pointers, and I am trying to write a deallocator for an object that to delete both the pointers in the array, and then delete the array itself. I define the array in the header of the object to be destructed like so
space* board[6][6];
I allocate the space objects in the array like so:
board[0][0]= new space(1,0);
board[0][1] = new space(1, 0);
board[0][2] = new space(1, 0);
My current destructor is like this
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j){
delete board[i][j];
}
delete[] board[i];
}
delete[] board;
When I do this, I get this message: Unhandled exception at 0x5080A9E8 (msvcr120d.dll) in Blitz.exe: 0xC0000005: Access violation reading location 0xFEEEFEE2.
I'm not quite sure what to do, I've tried looking around, and it seems like my destructor should be okay. I know if I had a decent programming education, I would use something better, like a vector or something else. I downloaded a pdf on how people actually use C++ these days, and I'll probably go over that soon, but I would just rather just take care of this memory leak and move on.

The board and board[i] variables should not be deleted because they have not been allocated by new.

You are mixing new with delete[]. The behaviour of your program is therefore undefined.
It would be marginally better if you used std::vector<std::vector<space>> instead. Then, the memory management would be done for you.
But if you're modelling a matrix then this is also not a good choice: it will have a "jagged edge" and the memory allocated is not contiguous.
A good alternative would be to allocate a contiguous block and use the convention (i * rows + j) for the element at (i, j). A std::vector<space> would suffice. Then consider using a 3rd party matrix library like BLAS (www.boost.org).

Related

Trying to deallocate a dynamic array of std::forward_list pointers (C++)

I'm trying to deallocate a dynamically allocated array of pointers to forward lists that was created with something like:
deck = new forward_list<T>*[numDecks];
for (int i = 0; i < numDecks; i++) {
deck[i] = new forward_list<T>;
}
numberOfDecks = numDecks;
I tried to iterate and delete the decks like this:
for (int i = 0; i < numDecks; i++) {
delete[] deck[i];
numberofDecks--;
}
delete[] deck;
But I got a read access violation. In fact, even if I just write:
delete[] deck[0];
I still get a read access violation. I've been playing around with this for quite some time and haven't been able to get it to work. I'm attaching a screenshot of the error (it appears in the forward_list file.
Thank you.
delete[] is for deleteing something that was allocated via new []. When you allocated something via new you need to delete it via delete.
There is no apparent reason for any manual dynamic allocations in your code. The std::forward_list already manages the memory of its elements. Storing pointers in the list has no advantage unless you need a level of indirection for some reason. And if you need it you should use smart pointers not raw ones. Also allocating the std::forward_list itself dynamically is most likely not needed (and again: use smart pointer if you do).
Your code has undefined behavior, as you are creating the std::forward_list objects using new but then destroying them with delete[] instead of delete. You need to change this:
delete[] deck[i];
To this:
delete deck[i];
new/delete are for single objects, and new[]/delete[] are for arrays. They must be matched up properly.
A better option is to use std::vector<std::forward_list> instead of std::forward_list*[], and let the vector handle the memory for you.

C++ deleting array on the heap

I'm having difficulty finding an answer on how to specifically perform this operation properly.
I'd like to better understand different ways to delete new memory allocated on the heap, especially in the instance of a two-D array.
For my example:
I have an array of size 5 on the stack consisting of int pointers (int *d[5]).
I initialize each of these int pointers in a loop to create and point to an int array of size 8 on the heap (d[i] = new int[8]).
I have now essentially created a two-D array (d[j][k]).
My question is what is the syntax for deleting only the individual arrays (int[8]) on the heap?
I currently have it as this, but when debugging it appears the arrays are not deallocated after it is performed...
for(int i = 0; i < 5; ++i)
delete d[i];
Should it be "delete [] d[i]" or just "delete [] d" or some other variation? Also, is there a way to delete the individual elements of the int[8] arrays? If anyone could concisely explain the syntax and their differences that would be super helpful. Thank you!
If you allocated arrays via d[i] = new int[8], then you must delete them via delete[] d[i]. There's no way to deallocate individual elements of such an array without deallocating the whole thing.
you mentioned that you are allocating the inner arrays within a loop. which I believe it looks something like this.
int*d[2];
for (int i = 0; i < 2; i++)
{
d[i] = new int[3];
}
Notice that d[2] contains just pointers to the arrays.
so in order to delete this array, you have to iterate through each set of array pointers
and call delete[] d[i];
for (int i = 0; i < 2; i++)
{
delete[] d[i];
}
As an additional note, it would be very advantageous to know how your IDE tries to detect memory corruptions.
for example in the visual studio (In DEBUG mode)
0xCD means Allocated memory via malloc or new but never written by
the application.
0xCC means uninitialised variables.
0XDD means memory has been released with delete or free.
0xFD means fence memory and acts as a guard. used for detecting indexing arrays that go out of bounds.
with that in mind lets see if we can make sense of what the IDE is doing when the above code is executed.
When the d array is declared int*d[2]; the memory layout looks like the following;
notice that d array has two elements but none of those have initial values so they are assigned to the 0xCC
lets see what happens after we do d[i] = new int[3];
notice that d array now has two elements each element contains an int array. the values you see are the address of the pointers to the array we allocated the memory for.
since we know what the addresses are we can look into the memory and see whats happening in there when allocating and deleting the each array.
for example after we allocate our second int array within the for loop, the memory location would look something like this;
notice that all the array element has 0xCD with ending of 0xFD.This would indicate in my IDE that the memory allocated and has a fence guards around it.
lets see what happens when the d[2] is deleted.

When should I use delete? (Consequences of not deleting after a dynamically created 2d array)

I am new to dynamic allocation and pointers. I will try to fill out a 2D dynamic array from a file and then apply a maze-solving algorithm (wall follower)on it.
Assuming I create a dynamically allocated 2D array like this:
int** board;
board = new int* [rowsize];
for(int row = 0; row < rowsize; row++)
{
board[row] = new int[colsize];
}
If I know that I won't be using this pointer for another variable, can I get away with not using delete for board ? If not what could potentially go wrong (If you are familiar with the wall follower algorithm) ? Also how do I delete a pointer to a pointer, would delete board be sufficient?
can I get away with not using delete for board?
Yes, but not for very long: repeated failure to delete arrays that your program allocates is a memory leak that eventually runs your process out of memory.
how do I delete a pointer to a pointer, would delete board be sufficient?
No, you will need to delete each pointer that you allocated and stored inside board:
for(int row = 0; row < rowsize; row++) {
delete[] board[row];
}
delete[] board;
Note square brackets after delete to indicate that you deleting an array, they are very important.
Allocating an deallocating memory for a rectangular matrix is a solved problem in C++ library. Switch to using a vector of vectors to avoid dynamic resource allocations:
std::vector<std::vector<int>> board(rowsize, std::vector<int>(colsize, 0));
If you don't delete the arrays you allocated they will continue to consume memory until the program is terminated. This might not technically be wrong, but it is wasteful.
With regard to deleting the board - no, it is not enough. You should delete every pointer you allocate with new:
for(int row = 0; row < rowsize; row++)
{
delete[] board[row];
}
delete[] board;
What you need to delete is the memory you allocated with new. That means that you don't deallocate the pointer itself, but the heap's memory it is pointing at.
So, you only need to do delete[] board. This will free up the int* array. It is not strictly necessary to use [] in this case, since it is a fundamental type array, but it is good practice to use it always for arrays, so you won't mess up when it's not like that.
Calling delete[] on an array will call the destructors of all objects inside the array itself, as well as freeing up the array. It is not necessary however for fundamental types.
Also note that you don't need to free the int** board. The pointer are variables like any other with some special capability, but they are allocated in the stack just like any other when you declare them like that.
Hope it helps :)

Which would be better: A unique_ptr to a 2D array or a 2D array of unique_ptrs?

I'm currently in the middle of making an old project of mine memory-safe.
In this project I have a 2D array populated with pointers to instances of my own class Block.
declared like so:
Block* gemGrid[xMax][yMax];
and populated later like so:
for(int i = 0; i<8; i++)
{
for(int j = 0; j<8; j++)
{
//do stuff here
gemGrid[i][j] = new Block(i,j, gridOffset);
}
}
This works fine.
I had the idea of creating a 2D array of unique_ptr<Block> instead of Block*.
Which i decided to declare like so:
unique_ptr<Block> gemGrid[xMax][yMax];
and populate like so:
for(int i = 0; i<8; i++)
{
for(int j = 0; j<8; j++)
{
gemGrid[i][j].reset( new Block(i,j, gridOffset));
}
}
However when I try this the compiler decides to completely ignore the second for loop (the 'j' incremented section), and create only a one dimensional array.
Which leads me to ask, does C++ have a problem with unique_ptrs in 2D arrays? And should I just stick with a 2D array of pointers to Blocks, and have one unique_ptr make sure this array is killed-of when it goes out of scope?
C++ has no objection whatever to a 2-D array of unique_ptr.
The two alternatives you offer don't seem like real alternatives to me. If you have a unique_ptr to a 2-D array of Block*, and you allocate xMax * yMax instances of Block using new and store pointers to them in your array, then who or what is going to free those instances of Block? Certainly the unique_ptr is not. So the answer to "should I just do that" is almost certainly "no", because you'll have memory leaks.
The most "obvious" way to allocate a 2-D layout of instances of Block is to define a 2-D array of Block (either using a builtin array or std::array if available). If you can identify anything about that that doesn't suit you, then someone can suggest an alternative way for your old code to avoid memory leaks.
[In response to a comment above] Having done Block gemGrid[xMax][yMax];, you can get a pointer to one of your Block objects, if you need one, like this: &gemGrid[i][j]. Needing a pointer has absolutely nothing to do with memory allocation. Pointers are the means by which new lets you access the objects it allocates, but you can take a pointer to an object regardless of how it is allocated.

Deleting an Array of Pointers - Am I doing it right?

I feel a little stupid for making a question about the deletion of pointers but I need to make sure I'm deleting in the correct way as I'm currently going through the debugging process of my program.
Basically I have a few arrays of pointers which are defined in my header file as follows:
AsteroidView *_asteroidView[16];
In a for loop I then initialise them:
for(int i = 0; i < 16; i++)
{
_asteroidView[i] = new AsteroidView();
}
Ok, so far so good, everything works fine.
When I eventually need to delete these in the destructor I use this code:
for(int i = 0; i < 16; i++)
{
delete _asteroidView[i];
}
Is this all I need to do? I feel like it is, but I'm worried about getting memory leaks.
Out of interest...
Is there much of a difference between an Array of Points to Objects compared with an Array of Objects?
This is correct. However, you may want to consider using Boost.PointerContainer, and save you hassle the hassle of manual resource management:
boost::ptr_vector<AsteroidView> _asteroidView;
for(int i = 0; i < 16; i++)
{
_asteroidView.push_back(new AsteroidView());
}
You do not have to manage the deletion, the container does that for you. This technique is called RAII, and you should learn about it if you want to have fun using C++ :)
About your edit: There are several difference, but I guess the most important are these:
An array of pointers can contain objects of different types, if these are subclasses of the array type.
An array of objects does not need any deletion, all objects are destroyed when the array is destroyed.
It's absolutely fine.
The rule of thumb is: match each call to new with an appropriate call to delete (and each call to new[] with a call to delete[])
Is this all I need to do? I feel like it is, but I'm worried about getting memory leaks.
Yes. The program is deallocating resources correctly. No memory leaks :)
If you are comfortable with using std::vector( infact it is easy ), it does the deallocation process when it goes out of scope. However, the type should be of -
std::vector<AsteroidView>
Given a class:
// this class has hidden data and no methods other than the constructor/destructor
// obviously it's not ready for prime time
class Foo {
int* bar_[16];
public:
Foo()
{
for (unsigned int i = 0; i < 16; ++i)
bar_[i] = new int;
}
~Foo()
{
for (unsigned int i= 0; i < 16; ++i)
delete bar_[i];
}
};
You won't leak memory if the constructor completes correctly. However, if new fails fails in the constructor (new throws a std::bad_alloc if you're out of memory), then the destructor is not run, and you will have a memory leak. If that bothers you, you will have to make the constructor exception safe (say, add a try ... catch block around the constructor, use RAII). Personally, I would just use the Boost Pointer Container if the elements in the array must be pointers, and a std::vector if not.