Reputation: 11
I am wondering whether there is an efficient way of re-purposing space in RAM.
Let's say my function creates four different arrays and 10 of variables in dedicated space. Then some other function is called, that zeroes the allocated space and creates its own structure, that is different. What are my options? Is there a straight-forward way of doing it?
Upvotes: 1
Views: 91
Reputation: 1
You don't allocate (at least on ordinary operating systems like Linux, Windows, MacOSX, etc...) in (physical) RAM, you allocate in virtual address space with system calls use by standard library allocating functions (e.g. malloc
in C, operator new
in C++). Read also Operating Systems: Three Easy Pieces to learn more about OSes.
On Linux, read about proc(5) and try cat /proc/self/maps
, cat /proc/$$/maps
and cat /proc/$$/smaps
to understand more about virtual address space. The main syscall to increase the virtual address space is mmap(2).
If you want to reuse in C++ some existing and valid address for a new (or another) data structure, you'll use the placement new
operator. Read more about operator new
. You probably want to call some destructor before reusing the space used by some object. Read also about union types, tagged unions and std::variant
Be aware of RAII programming idiom and of the rule of five.
Don't be shy to use pointers. In C++, prefer smart pointers most of the time. Learn more about the <memory>
header.
Upvotes: 2
Reputation: 393537
The straightforward way of doing it is using C. That's where this is "appropriate". In C++, don't.
In C++, the initialization function goes with the data type (known as constructor). And the allocation is done with new
, or better yet, new
is done by a container (such as a vector or a smart pointer).
Example:
#include <vector>
#include <iostream>
struct MyData {
int value;
std::string name;
MyData() : value(0), name("")
{ }
~MyData() {
if (!name.empty()) {
std::cout << "The element with name " << name << " is being destructed\n";
}
}
};
int main() {
std::vector<MyData> v(100); // allocates 100 MyData instances, all initialized to `0, ""`
v[5].value = 5;
v[5].name = "Five";
} // here, all of the vector is destructed and memory is correctly "de-allocated" (freed).
Prints:
The element with name Five is being destructed
The "automation" you see above is what makes C++ C++. It's a better language¹ with abstractions that make it so that you don't have to do all the work (and make it correct).
¹ objectively, compared to C. Of course, it can be used wrong, but the same goes for all languages.
Upvotes: 3