Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to partially deallocate memory?

Tags:

c++

c

free

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?

  • 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?
like image 898
Cam Avatar asked Dec 15 '10 07:12

Cam


People also ask

What happens if you don't deallocate memory?

If you don't deallocate this memory, you have a memory leak (memory that was allocated, but never deallocated, and therefore can't be used by your program in the future). Memory allocation/deallocation rule: IF YOU ALLOCATE IT (use a new), YOU MUST DEALLOCATE IT (delete it)!

How does free know how much memory to deallocate?

How does free() know the size of memory to be deallocated? The free() function is used to deallocate memory while it is allocated using malloc(), calloc() and realloc(). The syntax of the free is simple. We simply use free with the pointer.

When should you deallocate memory?

This means the memory is deallocated when the process finishes the execution and allocated again for the next process. The biggest disadvantage of this memory management technique is that there can be only one process executed at a time. Unless the deallocation of process happens, another process cannot be allocated.

Which is used to deallocate memory?

The "free" method in C is used to deallocate memory dynamically. The memory allocated by malloc() and calloc() is not automatically deallocated. As a result, the free() function is utilized anytime dynamic memory allocation occurs.


2 Answers

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

like image 65
On Freund Avatar answered Sep 25 '22 00:09

On Freund


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);
}
like image 33
fredoverflow Avatar answered Sep 26 '22 00:09

fredoverflow