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?
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 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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With