Pixel
Pixel

Reputation: 439

Is this deallocation correct?

Is this deallocation correct ?

vSize -> Dynamically the values will change for each and every run

// Allocation

int* xDump = new int(vSize);
int* yDump = new int(vSize);

// Deallocation

delete xDump;
delete yDump;

Is this deallocation correct?

Upvotes: 0

Views: 123

Answers (5)

miguel.martin
miguel.martin

Reputation: 1627

This is correct, as long as this:

int* xDump = new int(vSize);
int* yDump = new int(vSize);

was not supposed to be this:

int* xDump = new int[vSize];
int* yDump = new int[vSize];

If you are using square brackets, you're dynamically allocating an array. In this case, you would need to use the delete[] keyword. Like so:

delete[] xDump;
delete[] yDump;

EDIT:

If you really wanted a dynamically allocated array, it is recommended to use a std::vector, over creating one with new/delete.

For example, here's how you would use a vector in your situation:

std::vector<int> xDump(vSize);
std::vector<int> yDump(vSize);

// no need for delete[]

You should avoid owning pointers (pointers that point to memory allocated on the heap), instead try to use smart pointers, or the containers, in your code where necessary. As both smart pointers and containers take advantage of the very useful RAII pattern, which will reduce programmer errors (i.e. less chances of memory leaks) and increase exception safety.

Upvotes: 6

joy
joy

Reputation: 1569

This construct:

int* xDump = new int(vSize);

is equivalent to:

int* xDump = new int;
*xDump = vSize;

...the answer is yes, it is correct, because you are not allocating an array.

Upvotes: 0

fatihk
fatihk

Reputation: 7919

You need to call delete [] if you intend to delete an array which does not seem to be the case here. but if parameter vSize is in square brackets [] (may be you want this?) and then you definitely should call delete []

Upvotes: 0

Marius Bancila
Marius Bancila

Reputation: 16328

It seems that you are trying to allocate an array of ints, in which case it should be:

int* xDump = new int[vSize];
int* yDump = new int[vSize];

and

delete [] xDump;
delete [] yDump;

Upvotes: 3

Bart Friederichs
Bart Friederichs

Reputation: 33511

Yes, it is correct. No problems there.

Upvotes: 3

Related Questions