In C (or C++) I'm wondering if it's possible to partially deallocate a block of memory.
For example, suppose we create an array of integers a
of size 100,
int * a = malloc(sizeof(int)*100);开发者_C百科
and then later we want to resize a
so that it holds 20 ints rather than 100.
Is there a way to free only the last 80*sizeof(int) bytes of a
? For example if we call realloc, will it do this automatically?
- I'm looking for a solution that doesn't require moving/copying the first 20 ints.
- Alternatively, can you explain either why it would be bad if this were possible, or why the ability to do this wasn't included in either language?
You can use realloc, but you should definitely consider using STL containers instead of manually allocating memory.
We prefer RAII containers to raw pointers in C++.
#include <vector>
// ...
{
std::vector<int> a(100)
// ...
std::vector<int>(a.begin(), a.begin() + 20).swap(a);
}
I would prefer using a std::vector
. Let's enable C++0x:
std::vector<int> vec(20);
vec.reserve(100);
// do something
vec.shrink_to_fit();
From n3092 (not the so final draft, I need to get a fresh copy on this PC):
void shrink_to_fit();
Remarks: shrink_to_fit
is a non-binding request to reduce memory use. [ Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note ]
精彩评论