I have
int * array=new int[2];
and I would like to free the memory of the last element, thus reducing the allocated memory to only 1 element. I tried to call
delete array+1;
but it gives error
*** glibc detected *** skuska:
free(): invalid pointer: 0x000000000065a020 *
Can this be done in C++03 without explicit reallocation?
Note: If I wanted to use a class instead a primitive datatype (like int), how can I free the memory so that the destructor of the class is called too?
Note2: I am trying to implement vector::pop_back
Don’t use
new[]expression for this. That’s not how vector works. What you do is allocate a chunk of raw memory. You could use malloc for this, or you could use operator new, which is different from the new expression. This is essentially what thereserve()member function ofstd::vectordoes, assuming you’ve used the default allocator. It doesn’t create any actual objects the way thenew[]expression does.When you want to construct an element, you use placement new, passing it a location somewhere in the raw memory you’ve allocated. When you want to destoy an element, you call its destructor directly. When you are done, instead of using the
delete[]expression, you useoperator deleteif you usedoperator new, or you usefree()if you usedmalloc.Here’s an example creating 10 objects, and destoying them in reverse order. I could destroy them in any order, but this is how you would do it in a vector implementation.
pop_backwould be implemented by simply calling the destructor of the last element, and decrementing the size member variable by 1. It wouldn’t, shouldn’t (and couldn’t, without making a bunch of unnecessary copies) free any memory.