Cam
Cam

Reputation: 15234

Is it possible to partially deallocate memory?

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);

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?

Upvotes: 9

Views: 1437

Answers (3)

Matthieu M.
Matthieu M.

Reputation: 299960

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 ]

Upvotes: 2

fredoverflow
fredoverflow

Reputation: 263158

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);
}

Upvotes: 3

On Freund
On Freund

Reputation: 4436

You can use realloc, but you should definitely consider using STL containers instead of manually allocating memory.

Upvotes: 15

Related Questions