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?
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.
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;
Yes, it is correct. No problems there.
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 []
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.
Related
Let's say I have structure
struct Foo {
int whatever;
int whatever2;
...
};
And I have this type of array
Foo **array = new Foo*[128];
Then, to every pointer I assign new structure
for (int i = 0; i < 128; i++)
array[i] = new Foo;
Then, after a while I deallocate:
delete[] array;
How memory will be deallocated?
Only the space for pointers will be freed
Space for pointer + the objects pointed by those pointers themselves?
Your code leaks memory. You need to call delete once for every new call (assuming the new doesn't fail and either return NULL or throw bad_alloc). So, in this case, you'll need to have a similar loop to the one that calls array[i] = new Foo; that does delete array[i];
I think this is one of points in Scott Meyers book, Effective C++ have read long back. But basic idea is, to avoid memory leak when you use new. make sure to call delete as many times as new is called and map new with delete and new[] with delete[] accordingly. so in your case new is called 128 times in for loop and new[] is called once, so similarly delete should be called same way to array[i] 128 times and delete[] should be called once for array. Hope this helps.
I have an array of pointers (that I created by calling new ptr*[size]). All of these pointers point to an object that was also put on the heap.
What is the proper way to delete the array and all new'd ptr's?
This is what I do now:
for (int i = 0; i < size; i++) delete array[i];
delete[] array; // Not sure since this double deletes array[0]
Does this do what I think it should?
Thanks
Every pointer allocated with new gets a corresponding delete. Every pointer allocated with new [] gets a corresponding delete []. That's really all you need to know. Of course, when you have a dynamically allocated array which contains dynamically allocated pointers the deallocation must occur in reverse order.
So it follows that the correct idiom would be...
int main()
{
int **container = new int*[n];
for(int i = 0; i < n; ++i)
container[i] = new int[size];
// ... and to deallocate...
for(int i = 0; i < n; ++i)
delete [] container[i];
delete [] container;
}
And then of course I say "stop doing that" and recommend you use a std::array or std::vector (and the template type would be unique_ptr<int>).
Yes, that does what you think it should. Since you did new for each element, you have to delete each element. And since you did new[] for the entire array, you need to delete[] the entire array.
As #djechlin rightly says in the comments, there's not really enough information to go on, but I'm presuming your prior code is something like this:
int** array = new int*[5];
for (int i = 0; i < 5; i++) {
array[i] = new int;
}
Note that array is not actually an array type. It is a "pointer to pointer to int" and the array of pointers it points to was allocated with new[]. That's why you need to delete[] it.
Yes. First you have to free the object each pointer in the array points to, then you have to free the array itself. In that order. If you reverse the order you'll have no reference to the objects and will leak a lot of memory.
Yes, first you delete each object to which elements of array point, and then you delete array of pointers itself. If you want to check your memory management, you can use tools like valgrind, they will be able to spot most errors.
How do I delete this properly?
float** binsRowPtrs = new float *[_nbins];
The items are not dynamic created with new.
float** binsRowPtrs = new float *[_nbins];
for (int i = 0; i < _nbins ;i++)
{
binsRowPtrs[i] = (float*) (bins[i].row(y).data);
}
How do i delete this properly[?]
Properly? You use RAII and let something else handle the deletion for you. Depending on what you're trying to do, you may want to use:
std::vector<std::vector<float>>: an array of arrays of floats;
std::vector<float*>: an array of non-owning pointers to floats (i.e. something else handles correct allocation and deallocation);
or maybe just std::vector<float>: an array of floats.
The rule is:
Call as many delete or delete[] respectively as new or new[] you used and on the exact same addresses.
So if you just called new on binRowPtrs then you just need to call delete binRowPtrs.
However, in the part of your code which you didn't show us, If you used dynamic allocation through new for each of the array elements then you need to loop through the array and call delete on each of the element as well.
Note that ideally,
In C++ You should use dynamic allocations only when you cannot avoid them &
If et all you must, never use raw pointers, always use RAII through smart pointers to avoid the explicit memory management(you already noticed the perils of doing so in your case).
This will clear those pointers:
delete [] binsRowPtrs;
But the actual data you are storing with bins won't be touched.
Looking for some help with arrays and pointers and explanation of what I am trying to do.
I want to create a new array on the heap of type Foo* so that I may later assign objects that have been created else where to this array. I am having troubles understanding what I am creating exactly when I do something like the following.
Foo *(*f) = new Foo*[10];
Also once I have created my array how do I access each element for example.
(f + 9)->fooMember(); ??????
Thanks in advance.
Foo *(*f) = new Foo*[10];
The parentheses in the declaration are unnecessary, so this is the same as:
Foo **f = new Foo*[10];
In any case, the new Foo*[10] allocates space for ten Foo*s and leaves them uninitialized. It returns a pointer to the initial Foo* in the array (the zeroth element), which you assign to f.
To access elements of the array, you simply use subscripting:
f[0] = new Foo;
f[0]->fooMember();
Remember that anything you create using new[] must be freed once when you are done with it by calling delete[] on the pointer. For example:
delete[] f;
This does not delete the elements pointed to by the Foo*s in the array. If you create Foo objects using new, you must delete them before you delete the array. For example, to free the element we created above:
delete f[0];
You can create an array of pointers using the following code:
Foo** f = new Foo*[10];
Then access the elements with:
f[9]->fooMember();
Be sure to clean up afterwards:
delete[] f;
Thanks.
When you have this situation, you might find the following code snippet useful:
First the initialization:
Foo** f = new Foo*[10];
for (int i = 0; i < 10; i++) {
f[i] = new Foo;
}
Then to access each element in the f array which is what you asked, but you won't be able to do so unless you allocate memory properly for each member by calling the constructor as done above:
f[9]->fooMember();
Finally, to keep things tidy and to prevent memory leaks:
for (int i = 0; i < 10; i++) {
delete f[i];
}
delete[] f;
Arrays and pointers aren't very C++ish. How about
std::vector<std::shared_ptr<Foo> > f;
f.push_back(std::make_shared<Foo>(whatever, arguments, you, need));
// ...
f[9]->fooMember();
// ...
No manual cleanup needed :-)
When I compiled a code using the array name as a pointer, and I deleted the array name using delete, I got a warning about deleting an array without using the array form (I don't remember the exact wording).
The basic code was:
int data[5];
delete data;
So, what's the array form of delete?
The array form of delete is:
delete [] data;
Edit: But as others have pointed out, you shouldn't be calling delete for data defined like this:
int data[5];
You should only call it when you allocate the memory using new like this:
int *data = new int[5];
You either want:
int *data = new int[5];
... // time passes, stuff happens to data[]
delete[] data;
or
int data[5];
... // time passes, stuff happens to data[]
// note no delete of data
The genera rule is: only apply delete to memory that came from new. If the array form of new was used, then you must use the array form of delete to match. If placement new was used, then you either never call delete at all, or use a matching placement delete.
Since the variable int data[5] is a statically allocated array, it cannot be passed to any form of the delete operator.
As the other have said, you must use the vector form of delete:
void some_func(size_t n)
{
int* data = new int[n];
. . . // do stuff with the array
delete [] data; // Explicitly free memory
}
Be very wary of this, because some compilers will not warn you.
Even better, there is very rarely any need for using vector new/delete. Consider whether your code can be altered to make use of std::vector:
void some_func(size_t n)
{
std::vector<int> data(n);
. . . // do stuff with the array
} // memory held by data will be freed here automatically
And if you are dealing with the memory in a local scope, consider using STLSoft's auto_buffer, which will allocate from an internal buffer (held on the stack, as part of the instance) if possible, only going to the heap if it cannot:
void some_func(size_t n)
{
stlsoft::auto_buffer<int, 10> data(n); // only allocates if n > 10
. . . // do stuff with the array
} // memory held by data will be freed here automatically, if any was allocated
Read more about auto_buffer.
The code as shown has the array either on the stack, or in initialized part of the data segment, i.e. you don't deallocate it (which, as mentioned by others, would be "undefined behavior".) Were it on the "free store", you'd do that with delete [] data.
Just as RichieHindle stated above when you want to free the space dynamically allocated for an array pointed by data you have to put two brackets [] between the reserved word delete and the pointer to the beginning of the allocated space. Since data can point to a single int in memory as well as to the first element in the array this is the only way you let the compiler know that you want to delete the whole chunk of memory. If you don't do it the proper way the behaviour is "undetermined" (Stroustrup, The C++ Programming Language).
Fixes C4154 and C4156 warnings
float AR[5] = { 1.0f, 2.0f, ..., ..., ...};
delete [] & AR;