Leaking Memory

V

volk

Will this code leak memory? I hope I deleted the array correctly.

#include <iostream>

using namespace std;

int main()
{
//integers n and m represent the field
//n is rows and m is columns
int n = 5, m = 5;

int** field = new int*[n];

for(int i = 0; i < m; i++)
field = new int[m];

for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
field[j] = '.';




//deleting array row by row
for(int i = 0; i < m; i++);
delete[] field;

//deleting last object
delete[] field;

return 0;
}


Thank you
 
A

Alf P. Steinbach

* volk:
Will this code leak memory? I hope I deleted the array correctly.

#include <iostream>

using namespace std;

int main()
{
//integers n and m represent the field
//n is rows and m is columns
int n = 5, m = 5;

int** field = new int*[n];

for(int i = 0; i < m; i++)

This works as long as m == n, but you probably meant to write n, not m.

field = new int[m];

for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
field[j] = '.';
OK.


//deleting array row by row
for(int i = 0; i < m; i++);


Again, n, not m.

delete[] field;
OK.


//deleting last object
delete[] field;
OK.


return 0;
}


Instead you can do

#include <vector>
using namespace std;

int main()
{
int const n = 5;
int const m = 5;
vector< vector< int > > field( n, vector<int>( 5, '.' ) );

// Here use e.g. field[j]
// Automatically deallocated properly.
}

at least if memory serves me right. If it doesn't work right then check out the
std::vector constructors.

Tip: some typedef's can help too.


Cheers & hth.,

- Alf
 
J

Jorgen Grahn

Will this code leak memory? I hope I deleted the array correctly.

#include <iostream>

using namespace std;

int main()
{
//integers n and m represent the field
//n is rows and m is columns
int n = 5, m = 5;

int** field = new int*[n];

for(int i = 0; i < m; i++)
field = new int[m];

for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
field[j] = '.';

//deleting array row by row
for(int i = 0; i < m; i++);
delete[] field;

//deleting last object
delete[] field;

return 0;
}


I don't know, but my standard response to the constant stream of
people having trouble with C arrays: use std::vector and the problem
disappears.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top