Unable to delete object array c++ - c++

Hi I have a problem with deleting an object array.
Whenever I start my code, it works just fine, but when I close,
I am getting the error: 0xC0000005: Access violation reading location 0xcccccccc.
The code goes like this:
I initialize an instance of an object and immediately make an empty array out of it.
Class* classObject[15];
Afterwards, I define the empty array in a for loop.
for(int i = 0; i < 15; i++){
classObject[i] = new Class();
}
When the application closes, the following code should delete the array out of memory.
for(int i = 0; i < 15; i++){
delete classObject[i];
}
Instead of successfully closing, I am getting the Access violation error.
How can I fix this problem and where?
Also, are there maybe other ways I could create objects in a for loop?

class A
{
public:
A():a(0){};
private:
int a;
};
int main()
{
A* arr[15];
for(int i=0;i<15;i++)
{
arr[i] = new A();
}
for(int i =0;i<15;i++)
{
delete arr[i];
}
return 0;
}
There is no any error in my code .Have you delete the point before?

Related

Unlimited Object Creation in C++

While learning the dynamic object creation in C++ i have encountered a doubt . Here is my code.
And my question is , when the limiting condition in the loop is same as that of the no of objects created it works fine. But what happens when the loop works for more than the size given , it seems printing the values entered , but we have created only 4 objects and changed the condition of loop to more than 4
#include <iostream>
using namespace std;
class item{
int number;
public:
item(){
cout<<"Constructor"<<endl;
}
~item(){
cout<<"Destructor"<<endl;
}
void get_num(int num){
number = num
};
void show_num(){
cout<<"Number is "<<number<<endl;
}
};
const int size=4;
int main() {
item *itemObj = new item[size];
item *d = itemObj; //copy the address of itemObj inorder to access its member functions later
int tempNum;
for (int i = 0; i < size; ++i) {
cout<<"Enter the Number"<<endl;
cin>>tempNum;
itemObj->get_num(tempNum);
itemObj++;
}
//to print the numbers entered
for (int i = 0; i < size; ++i) {
d->show_data();
d++;
cout<<d<<endl;
}
delete itemObj;
return 0;
}
Your code isn't working fine at all. Because you change the value of the pointer that you requested from the new operator. When you call the delete for the itemObj at the last line, it doesn't have its original value.
So, instead of modifying the itemObj, you should modify the copy of it which is the pointer d here. Therefore, the problem isn't about the iteration amount of the loop. It's actually the violation on the heap memory.
Also, if you're creating a dynamic array, you should call delete [] instead of delete.

Deleting a dynamically allocated Array of Pairs throwing invalid address error

I have a very curious problem. I have a custom class Set, and a custom class Map (I have to recreate the standard library implementations for a class). In my map class, I create an array of pair<string, Set<string>>. But, when I expand my array of values and re-hash the values, I want to delete my old array. But, Whenever (and wherever in my code...) I try to, I get a Invalid address specified to RtlValidateHeap error. This happens even when the delete call is on the line after my new[] statement.
I have private class variable I call pair<string, Set<string>> *values;. Then in my constructor I do the following.
values = new pair<string, Set<string>>[tableSize];
Then when I got to delete values in a member function it threw the invalid address error. The code is below - I swap newValues, and values, then delete newValues in the reallocate() function. That is where the error is thrown
Node: the map is functioning perfectly. I can hash, store, and recall values without any errors.
Expanded Code:
template<>
class Map<std::string, Set<string>> : public MapInterface<string,Set<string>>{
public:
Map() {
numItems = 0;
tableSize = BonusHashTableSize;
values = new pair<string, Set<string>>[tableSize];
for (int i = 0; i < tableSize; ++i) {
values[i].first = "";
}
};
~Map() {
for (int i = 0; i < tableSize; ++i) {
if (values[i].first != "") {
values[i].second.clear();
}
}
delete[] values;
};
void reallocate() {
tableSize *= 2;
pair<string, Set<string>> *newValues = new pair<string, Set<string>>[tableSize];
for (int i = 0; i < tableSize; ++i) {
newValues[i].first = "";
newValues[i].second = Set<string>();
}
for (int i = 0; i < tableSize / 2; ++i) {
if (values[i].first != "") {
int newIndex = rehash(newValues, values[i].first);
newValues[newIndex].first = values[i].first;
newValues[newIndex].second = values[i].second;
Set<string> test = newValues[newIndex].second;
}
}
std::swap(values, newValues);
delete[] newValues;
//member functions
private:
pair<string, Set<string>> *values;
int tableSize;
int numItems;
};
Remove delete values from constructor. What is the purpose of allocation if you are just going to delete in the next line? And also you are using the deleted memory in the next for loop block.
Since you have deleted it here , it will cause invalid memory access error anywhere else because you are trying to delete already deleted memory location.

Destructing an array of arrays

I have a grid class as follows. Using it in my program works fine until the main() function returns then there is an error message and the program crashes due to an uncaught exception. If I comment out the destructor the class works just fine. What would be the correct way to implement this destructor?
If I just delete[] grid I assume that the arrays within it are not deallocated.
Exact error: Unhandled exception at 0x000869F5 in Battleship.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD.
class Grid
{
private:
int numRows;
int numCols;
char** grid; // array of arrays / pointer to pointer to char
public:
/*****************************************************************
Constructor()
*****************************************************************/
Grid() : numRows(0), numCols(0)
{
}
/*****************************************************************
Constructor(int, int)
*****************************************************************/
Grid(int numRows, int numCols) : numRows(numRows), numCols(numCols)
{
grid = new char*[numRows];
for (int arr = 0; arr < numRows; ++arr) {
grid[arr] = new char[numCols];
}
}
/*****************************************************************
Destructor NEEDS MAJOR EDIT AS IT IS CAUSING THE PROGRAM TO CRASH
*****************************************************************/
~Grid()
{
for (int i = 0; i < numRows; ++i)
{
delete[] grid[i]; //delete all subarrays of grid
}
delete[] grid; //delete grid
}
}

Pointer is initialized but I have error "Access violation reading location 0xCCCCCCCC". Why?

My function zeroPadding has more options but I put only two because they're important for this example. When I debug the main() function I got this error
Access violation reading location 0xCCCCCCCC
Why?
This is from the class Signal just to show what the constructor calls
template <class T> Signal<T>::Signal(int width,int height){
N=width;
M=height;
sig2D= new int*[N];
for(int i=0;i<N;i++){
sig2D[i]=new int[M];
}
t0=0;
deltaT=1;
for (int i=0;i<N;i++)
for (int j=0;j<M;j++){
sig2D[i][j]=t0+j*deltaT;
}
}
template <class T> Image<T>::Image(int width,int height): Signal(width,height) {}
template <class T> Image<T> Image<T>::zeroPadding(Image<T> im2){
Signal<T> s1= static_cast<Signal<T>>(*this);
Signal<T> s2= static_cast<Signal<T>>(im2);
int *temp=new int[15];
for(int i=0;i<15;i++){
temp[i]=0;
}
if(s1.getWidth()>s2.getWidth() && s1.getHeight()==s2.getHeight()){
im2.setWidth(s1.getWidth());
im2.sig2D=new T*[im2.getWidth()];
for(int i=0;i<im2.getWidth();i++){
im2.sig2D[i]=new T[im2.getHeight()];
}
for (int i=s2.getWidth();i<s1.getWidth();i++)
for(int j=0;j<s2.getHeight();j++){
im2.sig2D[i][j]=temp[j];
}
return im2;
}
else if(s1.getHeight()<s2.getHeight() && s1.getWidth()>s2.getWidth()){
setHeight(s2.getHeight());
sig2D=new T*[getWidth()];
for(int i=0;i<getWidth();i++){
sig2D[i]=new T[getHeight()];
}
for (int i=0;i<s1.getWidth();i++)
for(int j=s1.getHeight();j<s2.getHeight();j++){
sig2D[i][j]=temp[j];
}
(*this).zeroPadding(im2);
}
}
template <class T> Image<T> Image<T>::addImage(Image<T> im2){
Image<T> *r=new Image(80,80);
if ((*this).getWidth()==im2.getWidth() && (*this).getHeight()==im2.getHeight()) {
//r=new Image(im2.getWidth(),im2.getHeight());
for (int i=0;i<im2.getWidth();i++){
for(int j=0;j<im2.getHeight();j++)
(*r).sig2D[i][j]= (*this).sig2D[i][j]+im2.sig2D[i][j];
}
return(*r);
}
else {
(*r)= zeroPadding(im2); // here breaks why?
addImage(*r);
}
int main() {
Image<int> *a= new Image<int>(5,6);
Image<int> *b= new Image<int>(4,7);
(*a).addImage(*b);
return 0;
}
The most serious problem with your code is that you only return in the first if in zeroPadding which cause undefined returning value if the program flows into else.
if(s1.getWidth()>s2.getWidth() && s1.getHeight()==s2.getHeight()){
im2.setWidth(s1.getWidth());
im2.sig2D=new T*[im2.getWidth()];
for(int i=0;i<im2.getWidth();i++){
im2.sig2D[i]=new T[im2.getHeight()];
}
for (int i=s2.getWidth();i<s1.getWidth();i++)
for(int j=0;j<s2.getHeight();j++){
im2.sig2D[i][j]=temp[j];
}
return im2; // <- return here
}
else if(s1.getHeight()<s2.getHeight() && s1.getWidth()>s2.getWidth()){
// what will it return if the code comes to here
setHeight(s2.getHeight());
sig2D=new T*[getWidth()];
for(int i=0;i<getWidth();i++){
sig2D[i]=new T[getHeight()];
}
for (int i=0;i<s1.getWidth();i++)
for(int j=s1.getHeight();j<s2.getHeight();j++){
sig2D[i][j]=temp[j];
}
(*this).zeroPadding(im2);
}
// or here
But there are also many problems with your code
First, properties and methods in the same object don't need this, just sig2D[i][j], zeroPadding(im2);... is enough.
You're also generating lots of memory leaks by allocating memory without freeing. In the addImage function you create a new image
Image<T> *r=new Image(80,80);
then in the if you create a new image again without freeing the previous one
r=new Image(im2.getWidth(),im2.getHeight());
Besides, you're using allocated memory without checking for NULL
sig2D= new int*[N];
for(int i=0;i<N;i++){
sig2D[i]=new int[M];
}
int *temp=new int[15];
for(int i=0;i<15;i++){
temp[i]=0;
also in the addImage function, if it goes to the else
(*r)= zeroPadding(im2); // here breaks why?
if the new statement fails, the assignment also fails. And in the code you said it failed at the above line while in the comment you said it failed with (*this):
I when I called (*r)=(*r).zeroPadding(im2) instead of
(*r)=zeroPadding(im2) it passed so it's not problem with r, problem is
with (*this). I tought that (*this) is initialized in main(), am I
wrong?
Yes you're wrong. this is just a pointer to the current object, not a real variable, so if the object exists, access to this are always successful. But if r is not initialized then the line in your comment won't continue running.
Using -> instead of (*x). will make your code shorter and cleaner
Last, please refix the indent of your code

Vector push_back causing Unhandled exception

Everything is working until the compiler tries to perform the push_back operation.
in the if condition proper values are being returned.
I have declared items as:
vector<int> items; // inside the header file.
//inside the .cpp file
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
string temp = static_cast<ostringstream*>( &(ostringstream() << i) )->str(); // TO convert int i to a string temp
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}
the following error pops up:
Unhandled exception at 0x5052ad4a (msvcp100d.dll) in PrefixScan.exe: 0xC0000005: Access violation reading location 0x3d4cccd1.
PS: I have one more function using the push_back operation and there it's working fine.
Can anyone help me with this?
Even this gives the same error:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
items.push_back(i);
}
}
I think the issue is that the ostringstream is destructed when the static cast returns. Thus your pointer is dangling when str() is called. Try this instead:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
ostringstream blah;
string temp = (blah << i).str();
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}