0

So I am creating two different multidimensional vectors like this below

string **customdiceArray = new string*[crows];
for(unsigned int i = 0; i<crows;i++){
    customdiceArray[i] = new string[ccolumns];
}

They are giving me memory leaks however. I do a delete call like the one below for both vectors. Where am i going wrong?

//Deallocate create objects
delete diceArray;
diceArray = 0;

//set<string>* words = new set<string>;
delete words;
words = 0;

//string **customdiceArray = new string*[crows];
delete customdiceArray;
customdiceArray = 0;
unknown
  • 4,859
  • 10
  • 44
  • 62
Elblonko
  • 25
  • 4

2 Answers2

1

So if you want use delete in proper way here some examples:

For one variable

string *i = new string;
delete i;

For arrays (one dimension)

string *i = new string[10];
delete[] i;

For arrays (multi dimensions)

string **i = new *string[10]
for(int j=0; j<10;++j){
   i[j] = new string[10];
}

for(int j=0; j<10;++j){
   delete[] i[j];
}
delete[] i;
Ardel
  • 315
  • 2
  • 9
0

To avoid memory leaks and write C++ native code, you can also use std::vector instead of C arrays which needs more caution and maintenance.

for example:

vector<vector<int> > matrix;

vector<int> cols;
cols.push_back(1);
cols.push_back(2);
cols.push_back(3);

matrix.push_back(cols);
matrix.push_back(cols);

for(int i=0; i<matrix.size(); i++)
  for(int j=0; j<cols.size(); j++)
    cout << matrix[i][j] << endl;

Result:

1
2
3
1
2
3
Novin Shahroudi
  • 620
  • 8
  • 18